使用正则表达式的文字中无效的转义序列 [英] Invalid escape sequence in literal with regex

查看:68
本文介绍了使用正则表达式的文字中无效的转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一个字符串:

static let Regex_studio_tel = "^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$"

但是有一个问题:

文字中无效的转义序列

Invalid escape sequence in literal

我标记的图片:

编辑-1

我的要求是使用Regex匹配特殊的飞机号,例如:

My requirement is match special plane numbers use Regex, such as:

我公司有一个特殊的飞机号码:

My company have a special plane number:

028-65636688 or 85317778-8007  

// aaa-bbbbbbbb-ccc 我们知道 aaa 是前缀,它表示城市拨号代码,而 bbbbbbbb 是主要电话号码 cccc 是座机电话的分机号码

// aaa-bbbbbbbb-ccc we know the aaa is the prefix, and it means City Dialing Code, and bbbbbbbb is the main tel number, cccc is the landline telephone's extension number,

例如我公司的座机电话是 028-65636688 ,也许我们公司有10个分机号码: 028-65636688-8007,028-65636688-8006,028-65636688-8005 等.当然,它的末尾可能会有一个分机号.

such as my company's landline telephone is 028-65636688, maybe our company have 10 extension number: 028-65636688-8007 ,028-65636688-8006,028-65636688-8005 and so on. Of course, it maybe have a ext-number at the end.

028-65636688-2559

推荐答案

两个字符序列 \ -在Swift String中不是有效的转义序列.当需要将 \ -作为模式传递给 NSRegularExpression 时,需要在Swift String中编写 \\-文字.

Two character sequence \ - is not a valid escape sequence in Swift String. When you need to pass \ - to NSRegularExpression as pattern, you need to write \\- in Swift String literal.

因此,您的行应如下所示:

So, your line should be something like this:

static let Regex_studio_tel = "^(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?$"


添加

正如罗布(Rob)所说,减号不是出现在 [ ] 之外的正则表达式中的特殊字符,因此您可以将其写为:

As Rob commented, minus sign is not a special character in regex when appearing outside of [ ], so you can write it as:

static let Regex_studio_tel = "^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$"

这篇关于使用正则表达式的文字中无效的转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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