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

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

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}"]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值