Home > Net >  How can I use Regex to match optional characters only if the previous optional character matched?
How can I use Regex to match optional characters only if the previous optional character matched?

Time:10-27

For example: How do I match the words kein, keine, keiner or keines with regex.

I know how I can check for optional characters:

\bkein(?:e)?(?:r|s)?\b

But this way I would also match keins and keinr which is not what I want.

CodePudding user response:

You may use this regex:

\bkein(?:e[rs]?)?\b

RegEx Demo

Breakdown:

  • \b: Word boundary
  • kein: Match kein
  • (?:e[rs]?)?: Optional non-capture group to match e or er or es
  • \b: Word boundary

CodePudding user response:

You can create a list of possible suffixes like:

\bkein(e|er|es)?\b

CodePudding user response:

If it's just to know if a word responds to that pattern you can use

kein(e|er|es)?$
  • Related