If you wish to match -^!foo {}
, use (?:\s|^)([^\s\.]+(?=\s*\{))
.
If you wish to only match foo {}
, use (?:[^\w\.]|^)([^\W\.]+(?=\s*\{))
.
var pattern1 = /(?:\s|^)([^\s\.]+(?=\s*\{))/gm,
pattern2 = /(?:[^\w\.]|^)([^\W\.]+(?=\s*\{))/gm,
text = ".foo{} bar {} !!baz{} ..-boom {}",
match;
console.log('First pattern:');
while (match = pattern1.exec(text)) {
console.log(match[1]); // Prints "bar", "!!baz"
}
console.log('Second pattern:');
while (match = pattern2.exec(text)) {
console.log(match[1]); // Prints "bar", "baz", "boom"
}
Explanation of the first regex:
We expect the leading position before your word to either be the start
of the line ^
or whitespace \s
.
The word itself consists of repeated non-whitespace characters that
are not dots [^\s\.]
.
The word must be followed by a {
, for which we use lookahead
via (?=\{)
.
JavaScript's regex engine doesn't support lookbehind, so you have to use a non-capturing group (?:...)
to match the leading position before your word.
See JavaScript regular expressions and sub-matches for an explanation of how to access capturing groups
See https://regex101.com/r/bT8sE5/5 for a live demo of the regex with further explanation.