Reputation: 960
Im very new to Regex . Right now im trynig to use regex to prepare my markup string before sending it to the database.
Here is an example string:
@[admin](user:3) Testing this string @[hellotessginal](user:4) Hey!
So far i am able to identify @[admin](user:3)
the entire term here using /@\[(.*?)]\((.*?):(\d+)\)/g
But the next step forward is that i wish to remove the (user:3)
leaving me with @[admin]
.
Hence the result of passing through the stripper function would be:
@[admin] Testing this string @[hellotessginal] Hey!
Please help!
Upvotes: 5
Views: 638
Reputation: 110755
You can replace matches of the following regular expression with empty strings.
str.replace(/(?<=\@\[(.*?)\])\(.*?:\d+\)/g, ' ');
I've assumed the strings for which "admin"
and "user"
are placeholders in the example cannot contain the characters in the string "()[]"
. If that's not the case please leave a comment and I will adjust the regex.
I've kept the first capture group on the assumption that it is needed for some unstated purpose. If it's not needed, remove it:
(?<=\@\[.*?\])\(.*?:\d+\)
There is of course no point creating a capture group for a substring that is to be replaced with an empty string.
Javascript's regex engine performs the following operations.
(?<= : begin positive lookbehind
\@\[ : match '@['
(.*?) : match 0+ chars, lazily, save to capture group 1
\] : match ']'
) : end positive lookbehind
\(.*?:\d+\) : match '(', 0+ chars, lazily, 1+ digits, ')'
Upvotes: 0
Reputation: 2720
Try this:
var str = "@[admin](user:3) Testing this string @[hellotessginal](user:4) Hey!";
str = str.replace(/ *\([^)]*\) */g, ' ');
console.log(str);
Upvotes: 0
Reputation: 627469
You may use
s.replace(/(@\[[^\][]*])\([^()]*?:\d+\)/g, '$1')
See the regex demo. Details:
(@\[[^\][]*])
- Capturing group 1: @[
, 0 or more digits other than [
and ]
as many as possible and then ]
\(
- a (
char[^()]*?
- 0 or more (but as few as possible) chars other than (
and )
:
- a colon\d+
- 1+ digits\)
- a )
char.The $1
in the replacement pattern refers to the value captured in Group 1.
See the JavaScript demo:
const rx = /(@\[[^\][]*])\([^()]*?:\d+\)/g;
const remove_parens = (string, regex) => string.replace(regex, '$1');
let s = '@[admin](user:3) Testing this string @[hellotessginal](user:4) Hey!';
s = remove_parens(s, rx);
console.log(s);
Upvotes: 3