"Simple" regular expression

Started by
11 comments, last by deadlydog 16 years, 9 months ago
Awesome. Thanks for the replies guys! I tried both solutions and they both seemed to work the same. This is what I ended up using:

return new RegExp("^([^\"]|(\"(([^\"])*)\"))*\\b(" + _Word + ")\\b");

My problem now is that one of the functions which uses this regular expression, uses it to find an replace the given word. The problem is that this regular expression matches not only against the _Word, but also everything before it. So for example if I try to replace 'dogs' with 'apples' in the sentence "I like dogs and cats", instead of getting "I like apples and cats", I get "apples and cats". Does anybody know a way I can get around this so the regular expression matches only against the _Word, and not everything before it?

I thought about using the $1,$2,... parameters to try and remember all of the text before the _Word so I could replace the word with "$1$2$3$4 apples", but the $1 variables always appear to be blank (I was using 4 array values since there are 4 '(' brackets before the brackets around the _Word).

Any suggestions would be appreciated. Thanks.
-Dan- Can't never could do anything | DansKingdom.com | Dynamic Particle System Framework for XNA
Advertisement
Add another set of parentheses that contains the first pair as well as the * immediately after it. This will make $1 correspond to the part of the string that matched before the word. Each pair of parentheses corresponds to one of the $x values, with $0 being the whole string. So all you need is a pair of parentheses that captures everything before the word.
Quote:Original post by Vorpy
Add another set of parentheses that contains the first pair as well as the * immediately after it. This will make $1 correspond to the part of the string that matched before the word. Each pair of parentheses corresponds to one of the $x values, with $0 being the whole string. So all you need is a pair of parentheses that captures everything before the word.


Haha, I actually thought of this and tried it right before you posted about it, and it works. So for anyone who cares, this is what my final regular expression looks like:

return new RegExp("(^(?:[^\"]|(?:\"(?:(?:[^\"])*)\"))*)\\b(" + _Word + ")\\b", "i");

So everything before the word is stored in RegExp.$1, and the word itself is stored in RegExp.$2.

Thanks for all the help guys!!
-Dan- Can't never could do anything | DansKingdom.com | Dynamic Particle System Framework for XNA

This topic is closed to new replies.

Advertisement