Regexp problem

J

J Krugman

Suppose I have some lengthy and/or complicated sub-regexp such as
'(foo|bar|...)', how do I write a regexp that will match it, followed
by some white space, followed by something that is neither foo or
bar? I.e. I want this to match:

bar frobozz

but not this:

bar foo

TIA,

Jill
 
S

Sam Holden

Suppose I have some lengthy and/or complicated sub-regexp such as
'(foo|bar|...)', how do I write a regexp that will match it, followed
by some white space, followed by something that is neither foo or
bar? I.e. I want this to match:

By translating your english into perl regular expression syntax:

match it: (foo|bar|...)

white space: \s+

something: \S

neither foo or bar : (?!foo|bar)

The neither bit if the only not so common construct, see "perldoc perlre"
for details.


And putting it all together:

/(foo|bar|...)\s+(?!foo|bar)\S/s


I made a bunch of assumptions about what your words meant, things like
"some" being 1 or more, "something" being 1 or more non-whitespace
characters. If they are wrong, then the regex will be wrong.

I also assumed you didn't want:

"foo barn"

to match, but did want:

"foo seafood"

to match. Again, if that's wrong the regex is wrong (but easily fixed).
 
B

Benjamin Goldberg

J said:
Suppose I have some lengthy and/or complicated sub-regexp such as
'(foo|bar|...)', how do I write a regexp that will match it, followed
by some white space, followed by something that is neither foo or
bar? I.e. I want this to match:

bar frobozz

but not this:

bar foo

my $first_part = qr/foo|bar|.../;

my $regex = qr/$first_part \s+ (?!$first_part) \S/x;

I'm not entirely sure how perl optomizes this, so you might want to
prevent perl from backtracking over the \s+, as follows:

my $regex = qr/$first_part (?>\s+) (?!$first_part) \S/x;

This should only have a significant effect if you've got a string such
as "bar foo" (with lots of whitespace in between the two
parts). Without the (?>) it might take an excessive time to fail.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

help with regexp 5
static variable problem 7
Regexp problem 1
Getchar() problem 8
regexp(ing) Backus-Naurish expressions ... 7
thread problem 1
can this be done with generics? 32
Static variable problem 0

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,017
Latest member
GreenAcreCBDGummiesReview

Latest Threads

Top