簡體   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