RegExp searches: finding subexpressions

J

Jacob Weber

If I do a search with a regular expression that uses parenthesized
subexpressions, is there a way to find out where it found the
subexpressions?

For example, say I do:
"bb".search(/b(.)/g);

Those parentheses matched the second "b", at index 1. Is there any way
to find that out?

Jacob
 
D

Dietmar Meier

Jacob said:
If I do a search with a regular expression that uses parenthesized
subexpressions, is there a way to find out where it found the
subexpressions?

For example, say I do:
"bb".search(/b(.)/g);

Those parentheses matched the second "b", at index 1. Is there any way
to find that out?

You could use RegExp.exec() instead of String.search(), and then
add 1 (the length of the match preceding the parentheses) to the
"index" property of the result. If your Regular Expression is more
complex than the example given, you might have to parenthesize
any part of your Regular Expression that precedes the parentheses
you are interested in and then add the length of the strings of
the corresponding "1".. properties of the result of exec().

See the example in
http://doc.rz.ifi.lmu.de/web/js/CoreReferenceJS15/regexp.html#1194735

ciao, dhgm
 
J

Jacob Weber

Thanks. I'm trying to figure out a way that will work for any given
regular expression. Your idea about parenthesizing any part of the
expression before the first parentheses is interesting, although I'm
not sure it could be done automatically. I'll have to think about that.
 
D

Dietmar Meier

Jacob said:
I'm trying to figure out a way that will work for any given
regular expression.

I think this would be more complicated than you want it to be.
You'd have to do recursion for nested parentheses, and so on.

One advantage of using Regular Expressions is that you don't
have to care about character positions, so I don't really see
what you are trying this for.
Your idea about parenthesizing any part of the
expression before the first parentheses is interesting, although I'm
not sure it could be done automatically.

Of course that could only be simply done without consideration of non-
capturing parentheses and non-working if the first opening parenthesis
is within a character set or is escaped:

function addParentheses(rExp) {
var sExp = (rExp && rExp.source) || "",
rPar = /^(\^?)([^(]+)\(/,
bPar = rPar.test(sExp);
return new RegExp(bPar? sExp.replace(rPar, "$1($2)(") : sExp);
}

ciao, dhgm
 

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

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top