Frage

I would like to know if it is possible to have a regex that will check if 0 or on 1 of an array of words are present in a string. An exclusive OR with multiple entries...

Words that the string can contain 0 or only 1 :

  • Morning
  • Evening
  • Night

The following sentences should give the following result :

  1. This is a beautiful day => match (0 of the words)
  2. How are you this Morning ? => match (1 of the words)
  3. This Morning, it was the Night ! => not match (1 of the words)
  4. This Night, we will have a wonderful Morning => not match (2 of the words or more)

Thank you for your help!

War es hilfreich?

Lösung

Edit:

The pure regex solution should be something along the lines of:

string words = string.Join("|", yourWordsArray);
string regex = "^(?!.*\b(" + words + ")\b.*\b(" + words + ")\b).*\b(" + words + ")\b.*$";

/Edit

What you are asking is a "find every string that has NOT > 1 matches". In .Net this is rather easy, as you can have a construction like this:

return !(Regex.Matches("your text", "your regex").Count > 1)

and your regex would be something like:`

string regex = string.Join("|", yourWordsArray);

Not the prettiest of all code, but could be worse

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top