简体   繁体   中英

Replace characters inside a RegEx match

I want to match certain lines inside any text and inside that match, I want to replace a certain character as often, as it occurs. Sample Text:

Any text and "much" "more" of it. Don't replace quotes here
CatchThis( no quotes here, "any more text" , "and so on and so forth...")
catchthat("some other text" , "or less")
some text in "between"
CatchAnything ( "even more" , "and more", no quotes there, "wall of text")
more ("text"""") and quotes after...

Now I want to replace every quote inside the round brackets with, lets say, a hash sign. Desired outcome:

Any text and "much" "more" of it. Don't replace quotes here
CatchThis( no quotes here, #any more text# , #and so on and so forth...#)
catchthat(#some other text# , #or less#)
some text in "between"
CatchAnything ( #even more# , #and more#, no quotes there, #wall of text# )
more ("text"""") and quotes after...

Matching the lines is easy. Here's my pattern for that:

(?i)Catch(?:This|That|Anything)[ \t]*\(.+\)

Unfortunately, I have no idea how to match every quote and replace it...

The common approach to matching all occurrences of some pattern inside 2 different delimiters is via using \\G anchor based regular expression.

(?i)(?:\G(?!\A)|Catch(?:This|That|Anything)\s*\()[^()"]*\K"

See the regex demo .

Explanation :

  • (?i) - case insensitive modifier
  • (?: - a non-capturing group matching 2 alternatives
    • \\G(?!\\A) - a place in the string right after the previous successful match (as \\G also matches the start of the string, the (?!\\A) is necessary to exclude that possibility)
    • | - or
    • Catch(?:This|That|Anything) - Catch followed with either This or That or Anything
    • \\s* - 0+ whitespaces
    • \\( - a literal ( symbol
  • ) - end of the non-capturing group
  • [^()"]* - any 0+ chars other than ( , ) and "
  • \\K - a match reset operator
  • " - a double quote.

Do you really need to replace this inside regex? If your regex finds what you want, you can replace character on found string

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