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)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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With