开发者

how to match contents NOT include a string

开发者 https://www.devze.com 2023-03-07 16:26 出处:网络
the content is like this some content and some 123 %b1% and also some content %b2% %b3% and I want to match contents except %b1% or %b2% ...

the content is like this

some content and some 123 %b1% and also some content %b2% %b3%

and I want to match contents except %b1% or %b2% ...

I tried

([^(?:%b\d+%)]+)

but di开发者_Go百科gtal "123" will not be included.

how to matched the contents which NOT include "%b\d+" ?

thanks.


I think this is how it's done in PHP:

$str = "some content and some 123 %b1% and also some content %b2% %b3%";
$pattern = '/(?:^|(?!%b\d+%))(.*?)(?:%b\d+%|$)/';
preg_match_all($pattern, $str, $matches);
$match = implode($matches[0]);

If not, I'd be glad to hear what I'm doing wrong. In any case, I know the Ruby solution below works.


Original answer:

I wish I knew PHP better, but I'm sure it would be easy enough to figure out how to convert this Ruby code to PHP:

str = "some content and some 123 %b1% and also some content %b2% %b3%"
match = str.scan(/(?:^|(?!%b\d+%))(.*?)(?:%b\d+%|$)/).join

match then contains:

"some content and some 123  and also some content  "

The idea is to scan for all the matches of that regex, /(?:^|(?!%b\d+%))(.*?)(?:%b\d+%|$)/, and concatenate them; I don't know how PHP does that.


Your solution won't work as '[' and ']' define a list of characters to match (or not)

One solution would be to just negate the match

$var !~ /%b\d+%/

This will match everything that doesn't contain %b1%, %b2%... etc

0

精彩评论

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

关注公众号