简体   繁体   中英

Regular expression. Find strings that ends with these 2 particular special characters

{( Hi whats up? this is a first bracket: (... )}

Now, I want to fetch the text that is between the {( and )} characters.

I did this:

preg_match('/\{\(([^\)\}]+)\)\}/',$string,$match);

But it doesn't work. However, if I remove the ( which is inside the text, it works. But I will need the ( inside the texts.

How do I filter the texts between the {( and )} characters.?

Use .*? instead of [^\\)\\}]+

As a side-note, you could have used [^)}]+ because ) and } have no special meaning inside a character class.

Your regex works exactly as it should:

$string = '{( Hi whats up? this is a first bracket: (... )}';
preg_match('/\{\(([^\)\}]+)\)\}/',$string,$match);
var_dump($match[1]);

This produces the output ( see demo ):

string(44) " Hi whats up? this is a first bracket: (... "

Which is exactly what's between the strings {( and )} .

Notes:

  • You don't need to escape ) or } inside character classes. When inside a character class, they behave like normal characters and lose their meta-character properties. So instead of [^\\)\\}] , you could just use [^)}] .

  • If you want to simplify the regex, you can use /\\{\\((.*?)\\)\\}/ instead. This captures anything (.*?) between the strings. .* matches everything except newlines and the ? makes it non-greedy, so it matches as minimum as possible.

  • If your string spans multiple lines, then the current regex wouldn't work. You can use the s modifier to solve this. The s modifier changes the default behavior of the dot meta-character. With the s modifier set, a . will match newlines too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM