Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex starts and/or ends with string - how to simplify?

Tags:

regex

I have a string that might start and/or end with ;. I want to match and replace these ; strings. The following regex works, but how can I make it simpler?

(?:^(; ).*)(?:.*(; )$)|(?:^(; ).*)|(?:.*(; )$)

This uses the structure AB|A|B (A and B, or A, or B).

Example strings:

  • ; foo ;bar; (2 matches)
  • foo ;bar; (1 match)
  • ; foo ;bar (1 match)
  • foo ;bar (0 matches)
like image 902
Andrew Downes Avatar asked Nov 07 '16 12:11

Andrew Downes


1 Answers

Note that non-capturing groups are meant to group sequences of patterns, and if you do not quantify the group, nor use alternatives inside, the non-capturing group becomes redundant. So, you regex will look like ^(; ).*.*(; )$|^(; ).*|.*(; )$ without those groups and you easily see that there is a double .* in the first alternative. Reducing the pattern to ^(; ).*(; )$|^(; ).*|.*(; )$ you can see that if the first part is not matched, the second or third will find ; followed with a space either at the start or end, so the first alternative looks redundant (unless you need to split the replacement logic for 3 cases!).

So, if you just want to replace the match with 1 replacement pattern, you may just use

^;\s*|;\s*$

See the regex demo

like image 59
Wiktor Stribiżew Avatar answered Oct 20 '22 18:10

Wiktor Stribiżew