我有以下格式的字符串:
string test = "test.BO.ID";
我的目标是将字符串的第一个点之后的部分字符串化。 所以理想情况下,我期望输出为 "BO.ID"。
这是我尝试过的:
// Checking for the first occurence and take whatever comes after dot
var output = Regex.Match(test, @"^(?=.).*?");
我得到的输出是空的。
我需要为 Regex 做哪些修改?
最佳答案
你得到一个空输出,因为你的模式可以匹配字符串开头的空字符串,这就足够了,因为 .*?
是惰性子模式,而 .
匹配任何字符。
使用(值将在 Match.Groups[1].Value
中)
\.(.*)
或(通过前瞻,将字符串作为 Match.Value
)
(?<=\.).*
参见 regex demo和一个 C# online demo .
非正则表达式方法可以使用 String#Split
和 count
参数(demo):
var s = "test.BO.ID";
var res = s.Split(new[] {"."}, 2, StringSplitOptions.None);
if (res.GetLength(0) > 1)
Console.WriteLine(res[1]);
关于c# - 使用正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042633/