忽略转义的双引号字符 [英] Ignore escaped double quote characters swift

查看:172
本文介绍了忽略转义的双引号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NSPredicate 和正则表达式来验证电话号码。唯一的问题是在设置正则表达式时,Swift认为由于反斜杠,我正试图对其进行转义。我该如何解决?

I am trying to validate a phone number using NSPredicate and regex. The only problem is when setting the regex Swift thinks that I am trying to escape part of it due to the backslashes. How can I get around this?

我的代码如下:

let phoneRegEx = "^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$"


推荐答案

在Swift中,您仍然需要双斜杠转义在字符串文字中定义文字反斜杠:

In Swift, you still need to double-escape the slashes in string literals to define literal backslashes:

let phoneRegEx = "^((\\(?0\\d{4}\\)?\\s?\\d{3}\\s?\\d{3})|(\\(?0\\d{3}\\)?\\s?\\d{3}\\s?\\d{4})|(\\(?0\\d{2}\\)?\\s‌​?\\d{4}\\s?\\d{4}))(\\s?\\#(\\d{4}|\\d{3}))?$"

请参考正则表达式元字符表strings / regexp rel = nofollow noreferrer> ICU正则表达式 页,以查看应如何以这种方式对正则转义符进行转义。

Please refer to the Regular Expression Metacharacters table on the ICU Regular Expressions page to see what regex escapes should be escaped this way.

请介意正则表达式转义符(在上表中)与字符串文字转义符序列之间的区别,您可以在> 字符串文字中的特殊字符

Please mind the difference between the regex escapes (in the above table) and string literal escape sequences that you may check, say, at Special Characters in String Literals:


字符串文字可以包含以下特殊字符:

String literals can include the following special characters:


  • 转义的特殊字符 \0 (空字符), \\ (反斜线), \t (水平标签), \n (换行), \r (回车), \ (双引号)和 \'(单引号)

  • 任意Unicode标量值,写为 \u {n} ,其中 n 是1到8位的十六进制数字( Unicode

  • The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quotation mark) and \' (single quotation mark)
  • An arbitrary Unicode scalar value, written as \u{n}, where n is a 1–8 digit hexadecimal number (Unicode is discussed in Unicode below)

因此, \ 是用字符串文字形式表示的 字符串,您不必在正则表达式引擎中转义双引号,因此 \ 字符串文字正则表达式模式足以匹配字符串中的 char。但是, \\\ (表示 \ 文字字符串的字符串文字)也将匹配 字符,尽管您已经知道此正则表达式模式有多冗余。而且, \n (一个LF符号)以与 \\n 相同的方式匹配换行符,就像 \n 是换行符char的文字表示形式, \\n 是ICU正则表达式转义表中定义的正则表达式转义。

So, "\"" is a " string written as a string literal, and you do not have to escape a double quotation mark for the regex engine, so "\"" string literal regex pattern is enough to match a " char in a string. However, "\\\"", a string literal repesenting \" literal string will also match " char, although you can already see how redundant this regex pattern is. Also, "\n" (an LF symbol) matches a newline in the same way as "\\n" does, as "\n" is a literal representation of the newline char and "\\n" is a regex escape defined in the ICU regex escape table.

这篇关于忽略转义的双引号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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