I am working on a project and i want to split a string like below
DEV~Hi there is Sunday Tommorrow=1
I want to split this string as I want only text which is between the tilde(~) sign and equal sign(=). I also don't need ~ and = sign.
I have tried following code but not able to know how to split the string with tilde
obj.Code.Trim().Split('=')[1].Trim()
With the above code I can only split the string from = to sign but I want to remove the ~ sign and text on the left hand side also.
Can anyone suggest the solution?
-
1That's not splitting. You are trying to match a specific pattern. You need a regular expression for thisPanagiotis Kanavos– Panagiotis Kanavos2021年05月06日 07:02:21 +00:00Commented May 6, 2021 at 7:02
-
1Well, you can use Regex, but there would be also solutions without.Fildor– Fildor2021年05月06日 07:09:21 +00:00Commented May 6, 2021 at 7:09
4 Answers 4
Assuming your text would have exactly one tilde and equal sign, you may try the following string split:
string input = "DEV~Hi there is Sunday Tommorrow=1";
var match = Regex.Split(input, @"[~=]")[1];
Console.WriteLine(match); // Hi there is Sunday Tommorrow
Another approach, perhaps a bit more robust, would be to use a regex replacement:
string input = "DEV~Hi there is Sunday Tommorrow=1";
string match = Regex.Replace(input, @"^.*~(.*)=.*$", "1ドル");
Console.WriteLine(match); // Hi there is Sunday Tommorrow
Comments
You are trying to match a specific pattern. You need a regular expression for this. The expression ~.*= will match everything between ~ and =, including the characters:
~Hi there is Sunday Tommorrow=
To avoid capturing these characters you can use (?<=~).*(?==). The call Regex.Match(myString,"(?<=~).*(?==)") will catch just the part between the markers :
var match=Regex.Match(myString,"(?<=~).*(?==)");
Console.WriteLine(match);
-------------------------------
Hi there is Sunday Tommorrow
These are called look-around assertions. The first one, (?<=~) says that the match is precededed by ~ but the marker isn't included. The second one, (?==) says that the match is followed by = but again, the marker isn't included.
Another possibility is to use a group to capture the part(s) you want by using parentheses:
var m=Regex.Match(s,"~(.*)=");
Console.WriteLine(m.Groups[1]);
---------------------------------
Hi there is Sunday Tommorrow
You can use more than one group in a pattern
Comments
The proper way to do this is using RegEx, But a smiple soloution for this case:
obj.Code.Trim().Split('~')[1].Split('=')[0].Trim()
Comments
Try the below code:
obj.Code.Trim().Split('=')[0].Trim().Split('~')[1]