正则表达式模式匹配并在Swift中替换 [英] Regex pattern match and replace in Swift

查看:43
本文介绍了正则表达式模式匹配并在Swift中替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下字符串:

这是%1 $ s,产品%2 $ s 这是%2 $ s,产品为%2 $ s

我想用{0}替换%1 $ s ,并用{1}替换%2 $ s ,依此类推.

I want to replace %1$s by {0}, and %2$s by {1} and so on..

我试图做到:

let range = NSRange(location: 0, length: myString.count)
var regex = try! NSRegularExpression(pattern: "%[1-9]\\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XXXX")

任何人都可以帮助我!

推荐答案

您的模式是错误的,因为您的开头是 [a-z] ,所以您什么都没检测到.

Your pattern is wrong, you have at the start [a-z], so you aren't detecting anything.

此外,更喜欢使用NSStuff的utf16计数(因为使用NSString,它是UTF16)

Also, prefers utf16 count with NSStuff (because with NSString, it's UTF16)

let myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"

let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "{$1}")
print(newStr)

输出:

$>Hi this is {1}, product {2} Hi this is {2}, product {2}

关于%(\ d +)\ $ s 的一些解释(然后对Swift字符串重做 \ ).
:检测到%"
\ d + :检测号码(包括之前没有的12个号码)
(\ d +):检测编号,但在捕获组中
\ $ :检测"$"(需要转义,因为它是正则表达式中的特殊字符)
s :检测到"s"

Some explanation on %(\d+)\$s (and then redo a \ for Swift strings).
% : Detect "%"
\d+: Detect number (including 12 which weren't your case before)
(\d+): Detect number, but in a capture group
\$: Detect "$" (need an escape because it's a special char in regex)
s: Detect "s"

因此,有两组:整体(对应于整个正则表达式匹配项)和数字.第一个是$ 0,第二个是$ 1,这就是为什么我在模板中使用 {$ 1} .

So there are two groups: The whole (corresponding to the whole regex match), and the numbers. The first one would be $0, and the second one $1, that's why I used {$1} in the template.

注意:我使用 https://regex101.com 来检查模式.

NB: I used https://regex101.com to check the pattern.

使用增量,您将无法使用模板.您必须枚举所有匹配项,进行操作并替换.

With increment, you can't do it with the template. You have to enumerate all the matches, do the operation and replace.

var myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"
let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
let matches = regex.matches(in: myString, options: [] , range: range)
matches.reversed().forEach({ aMatch in
    let fullNSRange = aMatch.range
    guard let fullRange = Range(fullNSRange, in: myString) else { return }
    let subNSRange = aMatch.range(at: 1)
    guard let subRange = Range(subNSRange, in: myString) else { return }
    let subString = myString[subRange]
    guard let subInt = Int(subString) else { return }
    let replacement = "{" + String(subInt + 1) + "}"
    myString.replaceSubrange(fullRange, with: replacement)
})

这篇关于正则表达式模式匹配并在Swift中替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆