[英]What will be the regular expression for a string not starting with a substring
如果單詞不在字符串開頭,則匹配單詞的正則表達式將是什么? 例如,要匹配United
,字符串應為"We are United on it"
。 不應與"United States"
匹配。 我使用表達式\\w+\\s+(United)
但匹配時返回的are United
。 我只想讓United
匹配。
我將使用什么表達方式? 而且,當我替換匹配的表達式時,是否需要一個循環來替換多個匹配項?
以下是部分代碼:
var s = "We are United on it.";
var regex = new Regex(@"\w+\s+(United)", RegexOptions.IgnoreCase);
if (regex.IsMatch(s))
{
returnString = Regex.Replace(s,@"\w+\s+(United)" , "xyz");
}
任何代碼示例都將非常有幫助。 謝謝!
通常,當您想對比賽旁邊的內容強加條件但又不將文本包括在比賽中時,您需要一個斷言 ,例如
(positive or negative) (look-behind or look-ahead)
在這種情況下,我們想斷言比賽之前的事情,因此我們需要一個后向斷言。 而且由於我們要聲明的內容是:“就在比賽之前, 沒有字符串的開頭”,因此我們需要一個否定的后向聲明 :
string shouldPass = "We are United";
string shouldFail = "United we stand";
var regex = new Regex("(?<!^)United");
Console.WriteLine("{0} result: {1}", shouldPass, regex.IsMatch(shouldPass));
Console.WriteLine("{0} result: {1}", shouldFail, regex.IsMatch(shouldFail));
Console.ReadKey();
一看,后面的負斷言的語法(?<!text)
,替換text
,不管你說的只是在比賽前應該不會出現。
另外,您真的不需要分別調用.IsMatch
和.Replace
- .Replace
將在沒有匹配項的情況下不執行任何操作。
而且您不需要循環.Replace
將替換所有匹配項,除非您專門調用限制替換次數的重載。
(?<=\w+\s+)United
僅在可以找到字母數字的“單詞”和空格的情況下,才與United
匹配。
因此,
Console.WriteLine(Regex.Replace("We are united on it.", @"(?<=\w+\s+)United", "xyz", RegexOptions.IgnoreCase));
將導致
We are xyz on it.
具有不同邏輯的另一個版本(不確定需要哪個版本):
United(?!\s+States)
符合United
只有當它的后面沒有States
。
這些構造稱為環視斷言 。
Regex regexObj = new Regex(@"^\s*\w+\s+(United)");
這意味着從字符串的開頭開始,與您的單詞匹配之前,至少應有一些空格和一些字符。
問題是\\w+\\s+
也匹配,並且在那里也被替換了。 我認為最簡單的方法是將這部分放入捕獲組中,並將其也放入替換組中。
var s = "We are United on it.";
Console.WriteLine(Regex.Replace(s, @"(\w+\s+)United", "$1xyz", RegexOptions.IgnoreCase));
Console.ReadLine();
會打印
我們對此感到困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.