Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid escape sequence in literal with regex [duplicate]

Tags:

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:

enter image description here


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 
like image 211
aircraft Avatar asked Dec 28 '16 07:12

aircraft


2 Answers

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})?$" 
like image 98
OOPer Avatar answered Oct 08 '22 21:10

OOPer


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?

like image 39
Rob Avatar answered Oct 08 '22 22:10

Rob