我不知所措,我需要一些幫助。正則表達式:在預定義令牌之間讀取
的字符串看起來像:
"Hello World
@start some text @end
@start more text @end"
我需要一個正則表達式模式將匹配從@start
什麼第一@end
。在這個例子中,我們會有兩個匹配(@start (some text) @end
)。 @標籤內的文字可能包含換行符。
任何想法?
我不知所措,我需要一些幫助。正則表達式:在預定義令牌之間讀取
的字符串看起來像:
"Hello World
@start some text @end
@start more text @end"
我需要一個正則表達式模式將匹配從@start
什麼第一@end
。在這個例子中,我們會有兩個匹配(@start (some text) @end
)。 @標籤內的文字可能包含換行符。
任何想法?
此代碼:
string s = "Hello world\[email protected] text1 @end\[email protected] text2 @end";
Regex r = new Regex(@"(?<[email protected])[\s\S]*?([email protected])");
var mm = r.Matches(s);
產生2個匹配。
的招數是:
*?
,而不是僅僅*
)[\s\S]
匹配真正任何字符,包括換行符(?...)
)編輯:(得到了*向後固定呢?。)
(?<[email protected]).*?([email protected])
編輯:哎呦,使該SINGLELINE
「」默認情況下不會匹配換行符,但您可以啓用它。如何做到這一點取決於你正在使用哪個正則表達式引擎,但通常它被稱爲「單線」
編輯:看到你使用.NET。嘗試:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegexSandboxCSharp {
class Program {
static void Main(string[] args) {
string l_input = @"Hello World
@start some text @end
@start more text @end";
// This is the relevant piece of code:
MatchCollection l_matches = Regex.Matches(l_input, "(?<[email protected]).*?([email protected])", RegexOptions.Singleline);
foreach (Match l_match in l_matches) {
Console.WriteLine(l_match.Value);
}
Console.ReadKey(true);
}
}
}
@start {1}(。* \ n)+ @ end {1}。問題是(。* \ n)+部分,因爲它匹配結束。該模式返回一個匹配(開始一些文本結尾 開始更多文本結束) – mtm927
嘗試使用'。*?'而不是'。*'的非貪婪版本。順便說一句,你爲什麼需要'{1}'? – Vlad
沒有區別:( – mtm927