繁体   English   中英

匹配字符串直到特定的模式

[英]Match string until specific pattern

假设我有以下字符串:

“ hello world;一些随机文本; foo;”

我怎样才能选择所有内容,直到';'

换句话说,我希望第一场比赛是: "hello world"

第二个匹配是" some random text"

等等

我尝试过的事情:

string s = "hello world; some random text; foo;";
Regex r = new Regex(".+?;");
var match = r.Match(s);

while(match.Success)
{
    Console.WriteLine(match.Value.ToString());
    // first match is "hello world"!! but this turns out to be an infinite loop
    match.NextMatch();
}

我知道我可以使用Regex.Split()方法,但是我想使用此技术……我在做什么错? 为什么进行match.NextMatch(); 方法不返回下一个匹配项?

强烈建议您使用Regex.Split如你所指出的,甚至string.Split这个简单的例子。

但是,如果您仍然出于某种原因想要使用循环,则可以执行以下操作:

string s = "hello world; some random text; foo;";
Regex r = new Regex(".+?;");
for (Match m = r.Match(s); m.Success; m = m.NextMatch())
{
    Console.WriteLine(m.Value);
}

您的特定示例的问题是NextMatch返回新的匹配项。 它不会改变当前的匹配。 更改match.NextMatch(); match = match.NextMatch(); 在您的while循环中应该解决它。

这似乎解决了问题:

string s = "hello world; some random text; foo;";
Regex r = new Regex(".*?;{1}");
var match = r.Match(s);

while(match.Success)
{
    Console.WriteLine(match.Value.ToString());
    // move match index to avoid getting the same match
    match = r.Match(s, match.Index + match.Length);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM