简体   繁体   中英

Regex: how to replace a character inside a match pattern

I have a certain pattern

XXX >>> [a, b, c]

inside a huge chunk of text and I want to replace all "," in the matched texts only with say ".", so I get

XXX >>> [ab c]

Is it possible to do it with Regex only (c# flavor) and if yes how?

Updates:

I dont want to replace all comma with dots in the whole text! It is similar to this question, but it is unfortunately not the same: Ruby Regex - Need to replace every occurrence of a character inside a regex match and I have no problem identifying the pattern which consists of

  • prefix "XXX >>> ["
  • target body where commas needs to be replaced, eg "a, b, c, d"
  • suffix "]"

Solution: (?<=XXX >>> \\[|\\G)([^][,]*),(?=[^][]*\\])

The tricks are

  • \\G
  • Matching group statement

You can use this regex for search:

(?<=XXX >>> \[|\G)([^][,]*),(?=[^][]*\])

And use "$1." for replacement.

I would do this in two phases. First, grab the part of the line containing the commas to be replaced:

(XXX\s>>>\s)(\[[^\]]*\])

This captures two groups: the XXX >>> part, and the [a, b, c] part. Then, do a simple replace of comma->period on the second part. Finally, concatenate the two parts back together.

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