Invalid escape sequence in literal with regex [duplicate]

女生的网名这么多〃 提交于 2021-02-18 10:10:50

问题


I define a string with:

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

But there comes an issue:

Invalid escape sequence in literal

The picture I token:


Edit -1

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 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,

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

回答1:


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})?$"

ADDITION

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})?$"



回答2:


I'm guessing that your intent was to escape the - characters. But that's not necessary (and is incorrect). If your intent was to match just dashes, you should remove those backslashes entirely:

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

Unrelated, but I'm suspicious of that + character. Did you really mean that you wanted to match one or more occurrences of [2-9][0-9]{6,7}? Or did you want to match exactly one occurrence?



来源:https://stackoverflow.com/questions/41357169/invalid-escape-sequence-in-literal-with-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!