tags:

views:

27

answers:

2

I'm using http://regexpal.com/ and some of the look-ahead and look-behind are not supported in JavaScript.

is it still possible to use a matched criteria to signal the beginning of a match, and another for the end, without being included in the match.

for example, if I'm using [tag] to only get the tag, or if I have {abc 1,def} to match abc 1 and def

it's easy enough to get this when the string is short, but I would like it to find this from a longer string, only when this group is surrounded by { } and individual items surrounded by the ` character

A: 

If you don't have lookbehind as in JavaScript, you can use a non-capturing group (or no group at all) instead of the (positive) lookbehind. Of course this will then become a part of the overall match, so you need to enclose the part you actually want to match in capturing parentheses, and then evaluate not the entire match but just that capturing group.

So instead of

(?<=foo)bar

you could use

foo(bar)

In the first version, the match result bar would be in backreference $0. In the second version $0 would equal foobar, but $1 will contain bar.

This will fail, though, if a match and the lookbehind of the next match would overlap. For example, if you want to match digits that are surrounded by letters.

(?<=[a-z])[0-9](?=[a-z])

will match all numbers in a1b2c3d, but

[a-z]([0-9])[a-z]

will only match 1 and 3.

Tim Pietzcker
this all makes sense, but I'm unable to use **?<=** in javascript (or regexpal where I verify my regex)
Daniel
That's why I wrote "Instead of `(?<=...)` you could use..."
Tim Pietzcker
A: 

I suppose you can always use grouping:

m = "blah{abc 1, def}blah".match(/\{(.*?)\}/)

Where

m[0] = "{abc 1, def}"
m[1] = "abc 1, def"

That regexpal page doesn't show the resulting subgroups, if any.

R. Hill