Regex Exclusion
Moderator: General Moderators
Regex Exclusion
I have been mucking with this for several hours. Is it even possible to conditionally match text?
I want to match this..
#blah anything goes here#
But I don\\\'t want it to match this..
#blah anything | goes here#
I want to match this..
#blah anything goes here#
But I don\\\'t want it to match this..
#blah anything | goes here#
-
nickvd
- DevNet Resident
- Posts: 1027
- Joined: Thu Mar 10, 2005 5:27 pm
- Location: Southern Ontario
- Contact:
based on what you've already posted
should be all you need
Code: Select all
/#(.*?)#/That won't work because it will match even if there is a | between the #'s.nickvd wrote:based on what you've already posted
should be all you needCode: Select all
/#(.*?)#/
I already solved this issue a different way, but I'm still not clear on how to do exclusions in regex.
For example, if I want to match every thing encased in # signs, but only if it does not contain a pipe ( | ), how is this done? I've been reading regex documentation and haven't been able to figure it out.
Try this:
But you really need to give us a better definition so we can help better.
Code: Select all
$regex = '@#([^\|]*)#@U';First, the two .*? are useless since the [^\|] already means "any character except pipes".astions wrote:Hmm, that works. How does it work? I tried /#.*?[^\|].*?#/ and it didn't work. What did I do wrong?
Second, I used the U (PCRE_UNGREEDY) modifier - here is what the manual says about the U modifier:
U (PCRE_UNGREEDY)
This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).
Assuming we work with this string: just a test #catch me# and #catch me too#, without the U modifier the regex would have caught this:
catch me# and #catch me too
With the U modifier it will catch these:
1. catch me
2. catch me too
Hope that helps