[英]Regex match a line if a specific string occurs more than once in a line
我知道如何在一行中搜索兩個不同的特定字符串,但不知道如何檢查單個特定字符串是否在一行中出現多次。 可以這樣做嗎? 它是否匹配整行或者它是否與字符串本身匹配對我來說並不重要。
例:
我想指定'西班牙'並讓它匹配
西班牙人說西班牙語
但不是:
西班牙人說德語
這樣的事情可以用我不知道的正則表達式完成嗎? 如果沒有,有沒有辦法檢查逆,這基本上是相同的事情:
一個特定的字符串只在一行中出現一次嗎?
看起來很簡單:
Spani.+Spani
假設你在變量中有“Spani”
var toMatch = "Spani";
var pattern = $"{toMatch}.+{toMatch}";
(不要在toMatch
包含正則表達式特殊字符。)
您可以構建一個類似於@Steven Doggart上面評論中所述的正則表達式,以便最終得到: ^.*(Spani.*){2}$
您應該使用Regex.Escape
來確保不搜索任何正則表達式保留字符。
using System.Text.RegularExpressions;
public bool HasMatches(string input, string search, int times)
{
var pattern = $"^.*({Regex.Escape(search)}.*){{{times}}}";
return Regex.IsMatch(input, pattern, RegexOptions.Multiline);
}
並運行它:
var input = "The Spaniard speaks Spanish";
HasMatches(input, "Spani", 2);
input = "The Spaniard speaks German";
HasMatches(input, "Spani", 2);
input = "The Spaniard speaks Spanish" + Environment.NewLine + "The Spaniard speaks German";
HasMatches(input, "Spani", 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.