Swift替换子串正则表达式 [英] Swift replace substring regex

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

问题描述

我正在尝试使用正则表达式替换字符串中所有出现的英国汽车注册。

I am attempting to use regular expression to replace all occurrences of UK car registrations within a string.

以下swift代码适用于字符串匹配时正则表达式如下所示。

The following swift code works perfectly for a when the string matches the regex exactly as below.

var myString = "DD11 AAA"
var stringlength = countElements(myString) 
var ierror: NSError?
var regex:NSRegularExpression = NSRegularExpression(pattern: "^([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}$", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)!
var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "XX")
print(modString)

结果是 XX

但是,以下不起作用且字符串未修改

However, the following does not work and the string is not modifed

var myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
var stringlength = countElements(myString) 
var ierror: NSError?
var regex:NSRegularExpression = NSRegularExpression(pattern: "^([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}$", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)!
var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "XX")
print(modString)

结果是我的汽车注册1 - DD11 AAA我的汽车注册2 - AA22 BBB

任何人都可以给我任何指示吗?

Can anyone give me any pointers?

推荐答案

你需要删除 ^ $ 锚点。

^ 表示开始字符串 $ 表示字符串结尾(或线,取决于选项)。这就是你的第一个例子工作的原因:在第一个测试字符串中,字符串的开头后面跟着你的模式,并以它结束。

The ^ means start of string and $ means end of string (or line, depending on the options). That's why your first example works: in the first test string, the start of the string is really followed by your pattern and ends with it.

在第二个测试字符串中,模式位于字符串的中间,因此 ^ ... 无法应用。如果您只是删除 ^ $ 将适用于第二次出现的注册号,输出将是我的车注册1 - DD11 AAA我的车注册2 - XX

In the second test string, the pattern is found in the middle of the string, thus the ^... can't apply. If you would just remove the ^, the $ would apply on the second occurrence of the registration number and the output would be my car reg 1 - DD11 AAA my car reg 2 - XX.

let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options: NSRegularExpressionOptions.CaseInsensitive)
let range = NSMakeRange(0, myString.characters.count)
let modString = regex.stringByReplacingMatchesInString(myString, options: [], range: range, withTemplate: "XX")
print(modString)
// Output: "my car reg 1 - XX  my car reg 2 - XX"

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

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