[英]C# - Removing single word in string after certain character
我有一個字符串,我想刪除“ \\”之后的任何單詞,無論是中間還是結尾,例如:
testing a\determiner checking test one\pronoun
預期結果:
testing a checking test one
我嘗試了一個簡單的正則表達式,該正則表達式刪除了反斜杠和空格之間的所有內容,但是它給出了以下結果:
string input = "testing a\determiner checking test one\pronoun";
Regex regex = new Regex(@"\\.*\s");
string output = regex.Replace(input, " ");
結果:
testing a one\pronoun
看起來此正則表達式從反斜杠匹配到字符串中的最后一個空格。 我似乎無法弄清楚如何從反沖到下一個空格匹配。 另外,我不能保證最后有一個空格,所以我需要處理。 我可以繼續處理字符串,並在反斜杠后刪除所有文本,但我希望我可以一步完成兩個案例。
任何意見,將不勝感激。
將與任何字符匹配的.*
更改為僅與單詞字符匹配的\\w*
。
Regex regex = new Regex(@"\\\w*");
string output = regex.Replace(input, "");
“。*”匹配零個或多個任何類型的字符。 考慮改用“ \\ w +”,它匹配一個或多個“單詞”字符(不包括空格)。
使用“ +”代替“ *”將允許反斜杠后跟非“ word”字符保持不匹配。 例如,在句子“有時我遇到\\無法控制的強迫\\在句子中插入反斜杠\\字符!”中找不到匹配項!
在您當前的模式下, .*
告訴解析器是“貪婪的”,也就是說,要盡可能多地使用字符串,直到到達空格為止。 添加?
緊接着*
告訴它使捕獲盡可能小-一旦它到達第一個空間就停止。
接下來,您不僅要在空格處結束,而且要在字符串的空格處或結尾處結束。 $
符號捕獲字符串的結尾,並且|
意味着或。 使用括號將它們分組在一起,然后您的組共同告訴解析器在字符串的空格或結尾處停止。 您的代碼將如下所示:
string input = @"testing a\determiner checking test one\pronoun";
Regex regex = new Regex(@"\\.*?(\s|$)");
string output = regex.Replace(input, " ");
Try this regex (\\[^\s]*)
(\\[^\s]*)
1st Capturing group (\\[^\s]*)
\\ matches the character \ literally
[^\s]* match a single character not present in the list below
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\s match any white space character [\r\n\t\f ].
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.