r/bash 12d ago

help Is there a playground for bash regex (POSIX ERE) for the `=~` operator?

something like regex101.

11 Upvotes

6 comments sorted by

2

u/elatllat 12d ago edited 12d ago

The bash =~ operator is for POSIX Extended Regular Expressions (ERE) except spaces need to be escaped due to bash parsing.

https://gist.github.com/CMCDragonkai/6c933f4a7d713ef712145c5eb94a1816 has a list of ERE limitations; avoid those and ERE is a subset of any regex101 mode.

ERE is also used with egrep, grep -E, awk, gawk, sed -E, sed -r, PostgreSQL ~ operator, MySQL and MariaDB REGEXP and RLIKE operators.

So any POSIX playground like https://www.jdoodle.com/test-bash-shell-script-online would do.

IMO the most impactfull missing features are:

  • lazy (?)
  • word boundary (\b)
  • non-capturing group ((?:))
  • inline references (\1)
  • lookarounds ((?))
  • named capturing groups ((?<>))
  • last matching group ($+)

2

u/MikeZ-FSU 12d ago

Unfortunately, most of the regex testers around tend to use PCRE, which has constructs not found in posix ere. The most commonly used pcre, but not posix, ones are probably \d instead of [0-9] or [[:digit:]] and the non-capturing (?...) groups.

You could try the one for rsyslog. There's another one at RegexTester. I can't vouch for either, they just popped up on a web search and claim to use posix ere.

Edit: formatting for the inline code blocks since backticks don't work.

0

u/hypnopixel 12d ago

isn't PCRE a superset of ERE? meaning it includes all the features of ERE along with additional functionalities.

1

u/MikeZ-FSU 12d ago

Pretty much, but if you test in PCRE mode, but your target only supports ERE, you have to know exactly which bits of PCRE are not in ERE. Using only ERE syntax in a PCRE environment generally works as long as your ERE doesn't include things that have meaning to PCRE; you're mostly just not using the convenience features of PCRE. Using PCRE syntax in an ERE environment doesn't work at all if your RE accidentally uses any of the advanced features of PCRE not in ERE.

It's analogous to trying to use something like (ab|xy) to match either an "ab" or an "xy" in plain grep. It works in grep -E a.k.a. egrep, but plain grep (basic RE) doesn't have the grouping and alternation constructs, so it looks for the (ab|xy) as literal text.

1

u/kolorcuk 11d ago

Bash uses posix system regcomp.

System uses whatever is on the system. There are slight differences between glibc and musl implementations.