Can I add non-capture groups with a list of optional characters?

Viewed 70

I need to match strings which have a-z, \? or \*, for example:

abcd
abc\?d # mush have a \ in front of a ?
abc\*d
ab\?c\*d

and exclude strings which don't have \ in front of other punctuations, such as

abc?d
abc*d
ab?c*d

I tried [a-z(?:\\\?)(?:\\\*)]+ (https://regex101.com/r/5yYBDl/1), but it doesn't work, because [] only supports characters i guess.

Any help would be appreciated.

2 Answers

You may use this regex with an alternation and anchors:

^(?:[a-z]|\\[*?])+$

Updated RegEx Demo

RegEx Details:

  • ^: Start
  • (?:[a-z]|\\[*?])+: Non capturing group to match either [a-z] or \? or \*. Match 1 or more of this non capturing group.
  • $: End

will match Unicode character work? depending on your application it may have Unicode support

^(?:[a-z]|\u005c[\u003f\u002a])+$

https://www.regular-expressions.info/unicode.html
snippet from this site
"Perl, PCRE, Boost, and std::regex do not support the \uFFFF syntax. They use \x{FFFF} instead. You can omit leading zeros in the hexadecimal number between the curly braces. Since \x by itself is not a valid regex token, \x{1234} can never be confused to match \x 1234 times. It always matches the Unicode code point U+1234. \x{1234}{5678} will try to match code point U+1234 exactly 5678 times"

Related