By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,206 Members | 1,028 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,206 IT Pros & Developers. It's quick & easy.

RegExp searches: finding subexpressions

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Jacob Weber wrote:
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/Core...p.html#1194735

ciao, dhgm
Jul 23 '05 #2

P: n/a
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.

Jul 23 '05 #3

P: n/a
Jacob Weber wrote:
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
Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.