gpt4 book ai didi

swift - 如何将包含模式中其他文本的文本个性化并使用正则表达式进行编辑

转载 作者:行者123 更新时间:2023-12-04 07:26:23 32 4
gpt4 key购买 nike

我正在学习正则表达式,并且正在尝试创建一个替换特定模式的程序。
给定以下字符串:
@@@你好@!
我想识别“@@@”和“@!”并将它们替换为“***”和“*^”。这些字符之间的内容必须保持原样。
现在,我尝试了类似的东西:

text.replacingOccurrences(of: #"(@@@)"#, with: "***", options: .regularExpression)
text.replacingOccurrences(of: #"(@!)"#, with: "*^", options: .regularExpression)
但如果我的字符串是:

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


我的输出变成:

"**hello^ hello"


而所需的应该是:

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


事实上,我只希望字符在遵循模式时被替换:

@@@ some text @!


我用以下模式创建了一个正则表达式: #"(@@@)(?:\\.*?)(@!)"#但我无法获取文本并替换它。
如何在模式中对包含其他文本的文本进行个性化并对其进行编辑?

最佳答案

您可以使用

text = text.replacingOccurrences(of: #"(?s)@@@(.*?)@!"#, with: "***$1*^", options: .regularExpression)
regex demo .细节:
  • (?s) - 内联“单行”标志,使 .匹配任何字符
  • @@@ - 左侧分隔符
  • (.*?) - 捕获组 1($1 指此值):任何零个或多个字符尽可能少
  • @! - 右侧分隔符。

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

    关于swift - 如何将包含模式中其他文本的文本个性化并使用正则表达式进行编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68200479/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com