5

Suppose I have the following strings: cat I cat II cat III dog I dog III bird I

I would like to match all strings with a I, but NOT II or III.

So the correct match would give me:

cat I
dog I
bird I

I had the thought of matching an I with no other character after it, but perhaps there is a more direct way.

What would be the regex for such a pattern?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
yevg
  • 1,846
  • 9
  • 34
  • 70

4 Answers4

13

Try this sentence:

^(.*[^I])\I$

^ - begin of strings
(.*[^I]) - match any character other then 'I' ([^I] means "Do not catch 'I'")
\I - match an literal 'I'
$ - end of strings

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abe
  • 1,357
  • 13
  • 31
8

You can use word boundaries, so the regex can be like this:

^.*\bI\b.*$

Regex demo

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
5

Try this one:

^[a-z|A-Z|0-9]+[^I]\s?I{1}$

I think this is a more accurate solution.

Try demo

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ali Beshir
  • 412
  • 1
  • 6
  • 16
2

This is a possible solution:

^.*\bI\b$

This could be used like this in C#:

Regex regex = new Regex(@"^.*\bI\b$");
var input = new string[]{"cat I","cat II","cat III","dog I","dog III","bird I"};
foreach(string text in input)
{
    if (regex.IsMatch(text))
        Console.WriteLine(text);
}
Casperah
  • 4,504
  • 1
  • 19
  • 13