I'm sure this is simple, but I need to find single occurrences of the & character, but not any instances of &&.
Any explanation of exactly what the regular expression does would also be very helpful.
You didn't specify the flavor, but if it supports lookbehinds you can use:
(?<!&)&(?!&)
Despite the cryptic appearance the pattern is quite simple:
(?<!&) - Check the current position is not after an ampersand...& - ... match an ampersand...(?!&) - ...and check it isn't before an ampersand.You can do
([^&]|^)&([^&]|$)
Or to me more beautiful use lookarounds
(?<=[^&]|^)&(?=[^&]|$)
See it here online on Regexr
You have to check that there is no & before or the start of the string, and that there is no & ahead or the end of the string.
[^&] is a negated character class, meaning match anything but &
[^&]|^ match either a non & character or the start of the string (^)
[^&]|$ match either a non & character or the end of the string ($)
(?<=pattern) look behind assertion, ensures that pattern is before
(?=pattern) look ahead assertion, ensures that pattern is following
The difference between my first and my second solution is, the first one matches the characters before and ahead, the second solution uses look arounds which are zero width assertions, that mean they don't match a character, they just check that it us there.
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