简体   繁体   中英

Regex match multiple same expression multiple times

I have got this string {bgRed Please run a task, {red a list has been provided below} , I need to do a string replace to remove the braces and also the first word.

So below I would want to remove {bgRed and {red and then the trailing brace which I can do separate.

I have managed to create this regex, but it is only matching {bgRed and not {red , can someone lend a hand?

/^\\{.+?(?=\\s)/gm

Note you are using ^ anchor at the start and that makes your pattern only match at the start of a line (mind also the m modifier). .+?(?=\\s|$) is too cumbersome, you want to match any 1+ chars up to the first whitespace or end of string, use {\\S+ (or {\\S* if you plan to match { without any non-whitespace chars after it).

You may use

s = s.replace(/{\S*|}/g, '')

You may trim the outcome to get rid of resulting leading/trailing spaces:

s = s.replace(/{\S*|}/g, '').trim()

See the regex demo and the regex graph :

在此处输入图片说明

Details

  • {\\S* - { char followed with 0 or more non-whitespace characters
  • | - or
  • } - a } char.

If the goal is go to from

"{bgRed Please run a task, {red a list has been provided below}"

to

"Please run a task, a list has been provided below"

a regex with two capture groups seems simplest:

 const original = "{bgRed Please run a task, {red a list has been provided below}"; const rex = /\\{\\w+ ([^{]+)\\{\\w+ ([^}]+)}/g; const result = original.replace(rex, "$1$2"); console.log(result); 

\\{\\w+ ([^{]+)\\{\\w+ ([^}]+)} is:

  • \\{ - a literal {
  • \\w+ - one or more word characters ("bgRed")
  • a literal space
  • ([^{]+) one or more characters that aren't { , captured to group 1
  • \\{ - another literal {
  • \\w+ - one or more word characters ("red")
  • ([^}]+) - one or more characters that aren't } , captured to group 2
  • } - a literal }

The replacement uses $1 and $2 to swap in the capture group contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM