繁体   English   中英

正则表达式匹配在相同的字符串上返回不同的结果

[英]Regex match returning different results on identical strings

我有两个似乎相同的字符串,它们通过匹配返回不同的结果。 其中一个字符串是通过输入字段收集的,另一个是从 firebase ui auth 生成的本地存储中检索的。

有问题的正则表达式是/^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$/ /^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$/

localStorage.getItem("CurrentPhone")
-> "+1(631) 894-4396‬"
localStorage.getItem("CurrentPhone").match(phoneRegex)
-> null
"+1(631) 894-4396‬".match(phoneRegex) // Copied and pasted from result of calling localStorage.getItem("CurrentPhone")
-> null
"+1(631) 894-4396".match(phoneRegex) // Typing string
-> Array(6) [ "+1(631) 894-4396", "1", "631", "894", "4396", undefined ]

此外,我尝试修剪本地存储结果,并将其直接转换为字符串,两者都没有结果。 也许我错过了一些隐藏的角色?

解决了。 问题是保存到本地存储时附加的 U+202C 字符。 通过使用localStorage.getItem("CurrentPhone").replace(/[^\x00-\x7F]/g, "")清除非 ASCII 来解决

不知道为什么要附加这个,但在处理 firebase 身份验证时需要注意一些事项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM