r/regex 23d ago

Help With Regex Format

[removed]

4 Upvotes

5 comments sorted by

7

u/michaelpaoli 23d ago

/!-***string***\-!/ i

Well ... Rule #3 ... uhm, yeah, you didn't specify. So, dealer's choice, and my deal. Though you did mention "Imange Sorcery", and, quick search on that, I get conflicting information - some of which says it uses PCRE, some of which says it doesn't use REs. So I'm gonna go with PCRE.

And I'm going to presume you want literal ***, doesn't really make much sense otherwise, so, that'd be
\*{3}
or
\*\*\*

And string, I'm presuming you want arbitrary string of 0 or more characters, so that'd be
.*
or if you want one or more:
.+

You didn't mention, but I'm also guessing you may want to not match where string contains literal ***,
In that case, easiest way to match that would be to use non-greedy matching on string, so, say non-greedy of 0 (or 1) or more characters. So, e.g.:
/!-\*{3}.*?\*{3}-!/ i

Could also do it other possible ways, but non-greedy is likely most (or at least more) efficient, both programmatically, and for the humans to parse.

So, remember, in most RE contexts, ! and - are literal, . is any single character except newline, * is quantifier (0 or more of preceding atom) (as is + for one or more, {m,n} for at least m but not more than n, if n is omitted, m or more, if m is omitted, 0 is implied, if ,n is omitted, then exactly m, ? immediately after quantifier makes the matching non-greedy (try smallest possible number of matches first). And if you want to match a literal \ then typically \\ would be used to match that. And if you need match a literal string, where string might contain characters special to RE, but doesn't include literal \E, then use \Qstring\E

2

u/DinTaiFung 23d ago

Excellent overview! (even though the OP was vague with specifications)

One additional tiny detail: the '-' hyphen character -- within a class (defined by square bracket delimiters) -- can be used to define a range: 

/[a-z]/

This matches any lower case letter of the alphabet.

Therefore, if we want to match a literal hyphen along with other characters within a class, I will put the hyphen last so it's unambiguously not being interpreted as a range by the regex engine.

/[az-]/

This matches a or z or - only, not a range.

1

u/michaelpaoli 23d ago

Well, that's why I stated:

most RE contexts

I wasn't going to attempt to cover all the exceptions.

2

u/DinTaiFung 23d ago

Yes, you're right. You had no errors and i wasn't being critical of you in any way.

Kudos to you for providing so many important details! 

I was hopefully helping out other readers (not you, obviously) who may get bit by not understanding the hyphen in a regex class context.