简体   繁体   English

如果特定字符串在一行中出现多次,则正则表达式匹配一行

[英]Regex match a line if a specific string occurs more than once in a line

I know how to search for two different specific strings in one line, but not how to check if a single specific string occurs more than once in a line. 我知道如何在一行中搜索两个不同的特定字符串,但不知道如何检查单个特定字符串是否在一行中出现多次。 Can this be done? 可以这样做吗? Whether it matches the whole line or if it matches the strings themselves is not important to me. 它是否匹配整行或者它是否与字符串本身匹配对我来说并不重要。

Example: 例:

I would like to specify 'Spani' and have it match 我想指定'西班牙'并让它匹配

The Spaniard speaks Spanish 西班牙人说西班牙语

but not: 不是:

The Spaniard speaks German 西班牙人说德语

Can something like this be done with Regex that I am unaware of? 这样的事情可以用我不知道的正则表达式完成吗? If not, is there a way to check the inverse, which is basically the same thing: 如果没有,有没有办法检查逆,这基本上是相同的事情:

Does a specific string only occur once in a line? 一个特定的字符串只在一行中出现一次吗?

Seems like that would be pretty simple: 看起来很简单:

Spani.+Spani

Assuming you have "Spani" in a variable 假设你在变量中有“Spani”

var toMatch = "Spani";

var pattern = $"{toMatch}.+{toMatch}";

(Don't include Regex special characters in toMatch .) (不要在toMatch包含正则表达式特殊字符。)

You can build a regex similar to that noted in @Steven Doggart's comment above so that you end up with: ^.*(Spani.*){2}$ 您可以构建一个类似于@Steven Doggart上面评论中所述的正则表达式,以便最终得到: ^.*(Spani.*){2}$

You should use Regex.Escape to ensure you don't search for any regex reserved characters. 您应该使用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);
}

And run it like this: 并运行它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM