开发者

Regex to find & but not &&

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.


[^&]&[^&]

Something, which is not &, followed by &, followed by something else.

If your expression can be at the start or end of the line/input/expression/string, there are two more possibilities:

 ^&[^&] 
 [^&]&$

Now you can combine them with OR.


You need to find & which has something that is not a & or nothing both on its left and right side.

So the expression will be:

([^&]|^)&([^&]|$)

The first group matches a character that is not a & or the beginning of line. Then there's the character & and the second group matches a character that is not a & or the end of line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜