Regular expression to match words ending in either y or z, but not both.
I'm looking for a regex that matches words ending in y or z, but not both.
Here are some test cases:
fez day fyyyz fyyzy
- Compliant
fez
- Compliant
day
- Doesn't match
fyyyz
because it ends withyz
- Doesn't match
fyyzy
because it ends withzy
I tried this regex but it doesn't work.
[yz\b]
Regex Tool I am using is - http://www.regexr.com/
source to share
you can use
\b\w*[yz]\b(?<!yz)
or - if the word cannot end with yz
OR zy
:
\b\w*[yz]\b(?<!yz|zy)
It matches any word ending in y
or z
, but not yyz
(or with (?<!yz|zy)
, not those ending in yz
or zy
).
See regex demo
Note that the \b
inside of the square brackets is not a word boundary, but an escape sequence that matches the escape sequence.
Template details
-
\b
- upper word border -
\w*
- word symbols + + + (letters, numbers or_
, it can be customized to match letters with[^\W\d_]*
) -
[yz]
- ay
orz
-
\b
- final word boundary -
(?<!yz)
- negative lookbehind that does not match if there is a sequence ofyz
char immediately before the current location.
EDIT : now that all Perl, Python and Java tags are removed, this might also catch the attention of people who would like to use regex in VBA, C ++std::regex
(default is ECMAScript5) or JavaScript whose regex engines ( ECMA-5 standard ) do not support lookbehinds, but do support lookaheads.
you can use
/\b(?!\w*(?:yz|zy)\b)\w*[yz]\b/
See regex demo .
More details
-
\b
- upper word border -
(?!\w*(?:yz|zy)\b)
- negative result that is executed immediately after finding a word boundary, and it will fail if there is eitheryz
or or azy
final word boundary after 0 + word characters -
\w*
- use of word symbols + + -
[yz]
-y
orz
-
\b
is the final word boundary.
source to share