admin管理员组

文章数量:1355607

I’m to find a regular expression to match strings inside single but not multiple particular characters. For example:

this is =one= and =two= but not ==three== or ==four== etc

Here I’m using = as a delimiter, and I want to match the one and two because they’re inside single delimiters but not three or four because they’re inside multiple delimiters.

I thought using negative lookahead and lookbehind would do the trick:

/(?<!=)=(.+?)=(?!=)/g

but I end up matching the other strings as well, so I obviously don’t understand properly hot negative lookahead and lookbehind work. I thought the expression means = not preceded by a =, and so on.

A bigger test includes multiline strings:

this is =one= and =two= but not ==three== or ==four==.

====
this shouldn’t count at all
====

There might be another approach, which would be welcome, but one using lookahead and lookbehind would be more educational I think.

I’m using PHP and I plan to use the preg_replace_callback() function.

I’m to find a regular expression to match strings inside single but not multiple particular characters. For example:

this is =one= and =two= but not ==three== or ==four== etc

Here I’m using = as a delimiter, and I want to match the one and two because they’re inside single delimiters but not three or four because they’re inside multiple delimiters.

I thought using negative lookahead and lookbehind would do the trick:

/(?<!=)=(.+?)=(?!=)/g

but I end up matching the other strings as well, so I obviously don’t understand properly hot negative lookahead and lookbehind work. I thought the expression means = not preceded by a =, and so on.

A bigger test includes multiline strings:

this is =one= and =two= but not ==three== or ==four==.

====
this shouldn’t count at all
====

There might be another approach, which would be welcome, but one using lookahead and lookbehind would be more educational I think.

I’m using PHP and I plan to use the preg_replace_callback() function.

Share Improve this question asked Mar 28 at 7:42 ManngoManngo 16.6k13 gold badges104 silver badges148 bronze badges 2
  • =(.+?)= - the = match the "outer" of the double == here, but then .+ still allows = in that position as well. (?<!=)=([^=]+)=(?!=) should do the trick. – C3roe Commented Mar 28 at 7:55
  • @C3roe Of course, that was it. Can you turn that into an answer so that I can accept it? – Manngo Commented Mar 28 at 8:00
Add a comment  | 

1 Answer 1

Reset to default 3

=(.+?)= - the = match the "outer" of the double == here, but then .+ still allows = in that position as well.

(?<!=)=([^=]+)=(?!=) should do the trick.

本文标签: phpMatching text inside single but not multple delimiter characters in a regular expressionStack Overflow