I have this string: ](-test-word-another)
I'm trying to find every single occurrence of -
in between ]
and )
Basically the return should be: ](-
test-
word-
another)
Currently I have (?<=\]\()(-)(?=\))
but that just finds if there is only one -
Thank you in advance
CodePudding user response:
Try this: /(?<=\]. )-(?=. \))/gm
Test here: https://regex101.com/r/xkmTZs/1
This basically matches all -
only if they occur after a ]
and before )
.
CodePudding user response:
You can use
text.replace(/]\([^()]*\)/g, (x) => x.replace(/-/g, '_'))
See the demo below:
const text = 'Word-word ](-test-word-another) text-text-.';
console.log( text.replace(/]\([^()]*\)/g, (x) => x.replace(/-/g, '_')) );
The ]\([^()]*\)
regex matches a ](
substring, then any zero or more chars other than (
and )
and then a )
, and then all -
chars inside the match value (x
here) are replaced with _
using (x) => x.replace(/-/g, '_')
.
Another, single regex solution can look like
(?<=]\((?:(?!]\()[^)])*)-(?=[^()]*\))
See this regex demo. It matches any -
that is immediately preceded with ](
and any zero or more chars other than )
that does not start a ](
char sequence, and is immediately followed with any zero or more chars other than (
and )
and then a )
char.