crost
crost

Reputation: 192

How can I individuate the text that encloses some other text in a pattern and edit it with regex

I'm learning about regex and I'm trying to create a program where a certain pattern is substituted.

Given the following string:
@@@hello@!

I want to recognise "@@@" and "@!" and substitute them with "*** and "*^". What's between these characters must remain as it is.

Now, I tried something like:

text.replacingOccurrences(of: #"(@@@)"#, with: "***", options: .regularExpression)
text.replacingOccurrences(of: #"(@!)"#, with: "*^", options: .regularExpression)

but if my string is:

"@@@hello@! @@@hello@@@"

my output becomes:

"**hello^ hello"

while the desired one should be:

"**hello^ @@@hello@@@"

In fact I only want the characters to be substituted when they follow the pattern:

@@@ some text @!

I created a regex with the following pattern:
#"(@@@)(?:\\.*?)(@!)"#

but I'm not able to get the text and substitute it.
How can I individuate the text that encloses some other text in a pattern and edit it?

Upvotes: 2

Views: 59

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You can use

text = text.replacingOccurrences(of: #"(?s)@@@(.*?)@!"#, with: "***$1*^", options: .regularExpression)

See the regex demo. Details:

  • (?s) - an inline "singleline" flag that makes . match any char
  • @@@ - left-hand delimiter
  • (.*?) - Capturing group 1 ($1 refers to this value): any zero or more chars as few as possible
  • @! - right-hand delimiter.

Swift test:

let text = "@@@hello@! @@@hello@@@"
print(text.replacingOccurrences(of: #"(?s)@@@(.*?)@!"#, with: "***$1*^", options: .regularExpression))
// -> ***hello*^ @@@hello@@@

Upvotes: 2

Related Questions