Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let regex ignore everything between brackets?

Tags:

regex

php

Consider the following string:

I have been driving to {Palm.!.Beach:100} and it . was . great!!

I use the following regex to delete all punctuation:

$string preg_replace('/[^a-zA-Z ]+/', '', $string);

This outputs:

I have been driving to PalmBeach and it  was  great!!

But I need the regex to always ignore whatever is in between { and }. So the desired output would be:

I have been driving to {Palm.!.Beach:100} and it  was  great

How can I let the regex ignore what is between { and }?

like image 570
Pr0no Avatar asked Feb 09 '12 21:02

Pr0no


People also ask

How do you escape braces in regular expression?

If an opening bracket or brace is interpreted as a metacharacter, the regular expression engine interprets the first corresponding closing character as a metacharacter. If this is not the desired behavior, the closing bracket or brace should be escaped by explicitly prepending the backslash (\) character.

What is the difference between () and [] in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do you allow brackets in regex?

Well, you can just add them to the regex with something like [0-9. \)\(-]+ but, since you're complicating the expression, you'll probably need to check for balance as well. In other words, that regex is quite happy to accept 74.7((((((((((((2) which is not really well-formed.


2 Answers

Try this

[^a-zA-Z {}]+(?![^{]*})

See it here on Regexr

Means match anything that is not included in the negated character class, but only if there is no closing bracket ahead without a opening before, this is done by the negative lookahead (?![^{]*}).

$string preg_replace('/[^a-zA-Z {}]+(?![^{]*})/', '', $string);
like image 115
stema Avatar answered Oct 27 '22 19:10

stema


$str = preg_replace('(\{[^}]+\}(*SKIP)(*FAIL)|[^a-zA-Z ]+)', '', $str);

See also Split string by delimiter, but not if it is escaped.

like image 36
NikiC Avatar answered Oct 27 '22 19:10

NikiC