当前位置:   article > 正文

android 问号转义字符串,2019-04-22 使用字符串生成正则表达式注意问号的双重转义,然后用来split...

android ?号转义

定义一个从字符串生成正则表达式的函数:

function getRegex(str) {

return new RegExp(str, "ig");

}

测试使用问号作为参数的结果, 报错了,和日志中错误相同:

getRegex("?")

VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat

at new RegExp ()

at getRegex (:2:12)

at :1:1

getRegex @ VM50:2

(anonymous) @ VM66:1

尝试转义问号呢?

getRegex("\?")

VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat

at new RegExp ()

at getRegex (:2:12)

at :1:1

getRegex @ VM50:2

(anonymous) @ VM69:1

再次使用转义, 可以了

getRegex("\\?")

/\?/gi

其他情况?

getRegex("??")

VM50:2 Uncaught SyntaxError: Invalid regular expression: /??/: Nothing to repeat

at new RegExp ()

at getRegex (:2:12)

at :1:1

getRegex @ VM50:2

(anonymous) @ VM77:1

使用中括号表示可选?

getRegex("[?]")

/[?]/gi

str="https://visteria.vnative.net/5cb08a1689d4466c7080723c?p1={your-transaction-id}&source={your-sub-aff-id}"

"https://visteria.vnative.net/5cb08a1689d4466c7080723c?p1={your-transaction-id}&source={your-sub-aff-id}"

把正则表达式用来做split的参数

aa=getRegex("[?]")

/[?]/gi

str.split(aa)

(2) ["https://visteria.vnative.net/5cb08a1689d4466c7080723c", "p1={your-transaction-id}&source={your-sub-aff-id}"]

str.split(aa)[0]

"https://visteria.vnative.net/5cb08a1689d4466c7080723c"

最后重复一次对比

aa=getRegex("?")

VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat

at new RegExp ()

at getRegex (:2:12)

at :1:4

getRegex @ VM50:2

(anonymous) @ VM153:1

aa=getRegex("\?")

VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat

at new RegExp ()

at getRegex (:2:12)

at :1:4

getRegex @ VM50:2

(anonymous) @ VM156:1

aa=getRegex("\\?")

/\?/gi

str.split(aa)[0]

"https://visteria.vnative.net/5cb08a1689d4466c7080723c"

str.split(aa)

(2) ["https://visteria.vnative.net/5cb08a1689d4466c7080723c", "p1={your-transaction-id}&source={your-sub-aff-id}"]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/173975?site
推荐阅读
相关标签
  

闽ICP备14008679号