Reputation: 511
I need to write regExp for word should not start with and only select double quotes value output
e.g
notstart testing "testing" => no match
start testing "testing" => "testing"
anything testing testing => no match
I have written following regExp but it does not work with second scenario
^(?!notstart).*(?:\s+)".*"$
Upvotes: 2
Views: 58
Reputation: 56955
(?:\s+)
can be reduced to \s+
. /^(?!notstart).*".*"/
seems sufficient though. Ensure notstart
is not at the beginning, then validate that there are at least two quotes elsewhere in the string.
[
'notstart testing "testing"', // false
'start testing "testing"', // true
'anything testing testing' // false
].forEach(e => console.log(/^(?!notstart).*".*"/.test(e)));
If you want to capture the item in quotes:
[
'notstart testing "testing"', // null
'start testing "testing"', // "testing"
'anything testing testing' // null
].forEach(e => console.log(e.match(/^(?!notstart).*"([^"]*)"/)));
If you want spaces around the quoted word, you can use:
const pattern = /^(?!notstart).*(?:\s|^)"([^"]*)"(?:\s|$)/;
[
'notstart testing "testing"', // null
'start testing "testing"', // "testing"
'anything testing testing', // null
'anything testing"testing"', // null
'"foo"' // foo
].forEach(e => console.log(e.match(pattern)));
If you want to capture all quoted strings, this should avoid backtracking:
[
'notstart testing "testing"', // null
'start testing "testing"', // "testing"
'start testing "foo" "bar"', // "foo" "bar"
].forEach(e => {
let m;
if (!e.startsWith("notstart") &&
(m = [...e.matchAll(/"([^"]*)"/g)]).length) {
console.log(m);
}
else {
console.log(null);
}
});
Upvotes: 1
Reputation: 785156
Modern Javascript browsers support dynamic length lookbehind assertions. Hence you may consider this regex:
/(?<!^notstart.*?)"[^"]*"/gmi
(?<!^notstart.*?)
: Negative lookbehind assertion to fail the match if a match has notstart
at line start."[^"]*"
: Match a quoted word. (This doesn't take care of escaped or unbalanced quotes).Upvotes: 3