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/

+3


source to share


4 answers


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]

    - a y

    orz

  • \b

    - final word boundary
  • (?<!yz)

    - negative lookbehind that does not match if there is a sequence of yz

    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 either yz

    or or a zy

    final word boundary after 0 + word characters
  • \w*

    - use of word symbols + +
  • [yz]

    - y

    orz

  • \b

    is the final word boundary.
+4


source


\b\w*[yz](?<!(?:yz|zy))\b

      

Try this.Lookbehind make sure you don't have yz or zy

both end.See demo.



https://regex101.com/r/Gtplnq/1

+2


source


If your word is not 1 in length, use:

/\b\w*(?:[^z]y|[^y]z)\b/

      

RegEx Demo 1

If you also have 1 character word, you can use this negative expression for regular expressions:

/\b(?!\w*(?:yz|zy)\b)\w*[yz]\b/

      

RegEx Demo 2

+1


source


Another way, without lookbehinds:

/\w*(?:[^y]z|[^z]y)\b/

      

Example

+1


source







All Articles