'Regex that counts words but ignores words encased in curly braces
I am absolutely horrible with regex and avoid it when i can, however i can but this seems suitable for a bit of regex. What i am interested in is counting the number of words in a string excluding words encased in {}
Example:
input : someting test whatever {not} and also {not you}output : someting test whatever and also
My best try was
\w+(?![^{}]*})
Solution 1:[1]
You can match braces remove them using javascript. Just note, like cyberbrain's comment, this won't be robust for many nested braces.
const p = 'someting test whatever {not} and also {not you}'
const regex = /{.*?}/g;
console.log(p.replace(regex, ''));
// expected output: "someting test whatever and also"
Note the double-space in the output, because {not} is removed but not the spaces around it.
To explain the regex:
- The
/s are the regex's delimiters. - The
gat the end is a global flag, indicating the replace should act on every match in the input string, not just the first match. .*?:.means any character*?means to match any 0 or more of what came before it, but the?makes it "lazy", meaning it'll return the shortest match found.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | will |
