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

查看:48
本文介绍了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)

结果是my car reg 1 - DD11 AAA my car reg 2 - AA22 BBB

谁能给我指点一下?

推荐答案

您需要删除 ^$ 锚点.

You need to remove the ^ and $ anchors.

^ 表示字符串的开头$ 表示字符串的结尾(或行,取决于选项).这就是您的第一个示例有效的原因:在第一个测试字符串中,字符串的开头实际上是您的模式并以它结尾.

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.

在第二个测试字符串中,模式位于字符串的中间,因此^... 不适用.如果您只删除 ^$ 将应用于第二次出现的注册号,输出将是 my car reg 1 - DD11 AAA my汽车 reg 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: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, myString.count)
let modString = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XX")
print(modString)
// Output: "my car reg 1 - XX  my car reg 2 - XX"

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

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