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