0

I want to find if word terminate with 's or 'm or 're using regular expression in c#.

if (Regex.IsMatch(word, "/$'s|$'re|$'m/"))
   textbox1.text=word;
Kristoffer Jälén
  • 4,112
  • 3
  • 30
  • 54
Programmer
  • 39
  • 5

1 Answers1

0

The /$'s|$'re|$'m/ .NET regex matches 3 alternatives:

  • /$'s - / at the end of a string after which 's should follow (this will never match as there can be no text after the end of a string)
  • $'re - end of string and then 're must follow (again, will never match)
  • $'m/ - end of string with 'm/ to follow (again, will never match).

In a .NET regex, regex delimiters are not used, thus the first and last / are treated as literal chars that the engine tries to match.

The $ anchor signalize the end of a string and using anything after it makes the pattern match no string (well, unless you have a trailing \n after it, but that is an edge case that rarely causes any trouble). Just FYI: to match the very end of string in a .NET regex, use \z.

What you attempted to write was

Regex.IsMatch(word, "'(?:s|re|m)$")

Or, if you put single character alternatives into a single character class:

Regex.IsMatch(word, "'(?:re|[sm])$")

See the regex demo.

Details

  • ' - a single quote
  • (?: - start of a non-capturing group:
    • re - the re substring
    • | - or
    • [sm] - a character class matching s or m
  • ) - end of the non-capturing group
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Why do you have `$` in the end of pattern? OP says *if **word** terminate* - not a string. :) – JohnyL Dec 09 '18 at 19:44
  • @JohnyL See [OP comment](https://stackoverflow.com/questions/53685367/find-terminate-word-using-regular-expression/53695310?noredirect=1#comment94227635_53685367): *go to for loop to bring the next word.* OP is testing "words" as **separate strings** against the regex. – Wiktor Stribiżew Dec 09 '18 at 20:22