CodeMonkey
CodeMonkey

Reputation: 300

Regex to Match Phrase ending with a question mark

I'm trying to figure out a javascript regex that'll match an exact phrase that ends with a question mark, but isn't wrapped in quotes. So far I have this, which matches the phrase "some phrase", but I can't figure out how to match "some phrase?". Any help would be greatly appreciated.

(?<!"|')\some phrase\b(?!"|')

Upvotes: 0

Views: 1854

Answers (2)

Rob W
Rob W

Reputation: 349042

Lookbehinds don't exist in JavaScript. Use the following pattern:
(?:[^"']|^)(some phrase\?)(?!["']). [^"']|^ means: any non-quote character or the beginning of a string.

Example:

var text = "....";
var pattern = /(?:[^"']|^)(some phrase\?)(?!["'])/;
var string = text.match(pattern);
var desiredString = string[1]; //Get the grouped text

var patternWithNQuoteGrouped = /([^"']|^)(some phrase\?)(?!["'])/;//Notice: No ?:
var replaceString = text.replace(patternWithNQuoteGrouped, '$1$2');
//$1 = non-quote character $2 = matched phrase

The parentheses around the phrase mark a referable group. (?: means: Create a group, but dereference it. To refer back to it, see the example code. Because lookbehinds don't exist in JavaScript, it's not possible to create a pattern which checks whether a prefix does not exist.

Upvotes: 2

gilly3
gilly3

Reputation: 91497

Try this:

var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
    var matchingPhrase = RegExp.$2;
}

http://jsfiddle.net/gilly3/zCUsg/

Upvotes: 1

Related Questions