简体   繁体   中英

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

var toMatch = "Spani";

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

(Don't include Regex special characters in toMatch .)

You can build a regex similar to that noted in @Steven Doggart's comment above so that you end up with: ^.*(Spani.*){2}$

You should use Regex.Escape to ensure you don't search for any regex reserved characters.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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