[英]how to split a string using c#
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?任何人都可以提出解决方案吗?
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
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:调用
Regex.Match(myString,"(?<=~).*(?==)")
将仅捕获标记之间的部分:
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您可以在一个模式中使用多个组
The proper way to do this is using RegEx, But a smiple soloution for this case:正确的方法是使用正则表达式,但对于这种情况有一个简单的解决方案:
obj.Code.Trim().Split('~')[1].Split('=')[0].Trim()
Try the below code:试试下面的代码:
obj.Code.Trim().Split('=')[0].Trim().Split('~')[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.