Reputation: 175
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?
Upvotes: 2
Views: 332
Reputation: 131180
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
Upvotes: 2
Reputation: 121
Try the below code:
obj.Code.Trim().Split('=')[0].Trim().Split('~')[1]
Upvotes: 1
Reputation: 520888
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
Upvotes: 3
Reputation: 163
The proper way to do this is using RegEx, But a smiple soloution for this case:
obj.Code.Trim().Split('~')[1].Split('=')[0].Trim()
Upvotes: 1