相关疑难解决方法(0)

Javascript中是否有RegExp.escape函数?

我只想用任何可能的字符串创建一个正则表达式.

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);
Run Code Online (Sandbox Code Playgroud)

有内置的方法吗?如果没有,人们会用什么?Ruby有RegExp.escape.我觉得我不需要自己编写,那里必须有标准的东西.谢谢!

javascript regex

404
推荐指数
10
解决办法
10万
查看次数

以特殊字符开头或结尾的单词的单词边界会产生意想不到的结果

假设我想匹配短语Sortes\index[persons]{Sortes}中短语的存在test Sortes\index[persons]{Sortes} text。

使用 pythonre我可以做到这一点:

>>> search = re.escape('Sortes\index[persons]{Sortes}')
>>> match = 'test Sortes\index[persons]{Sortes} text'
>>> re.search(search, match)
<_sre.SRE_Match object; span=(5, 34), match='Sortes\\index[persons]{Sortes}'>
Run Code Online (Sandbox Code Playgroud)

这有效,但我想避免搜索模式Sortes对短语给出肯定的结果test Sortes\index[persons]{Sortes} text。

>>> re.search(re.escape('Sortes'), match)
<_sre.SRE_Match object; span=(5, 11), match='Sortes'>
Run Code Online (Sandbox Code Playgroud)

所以我使用\b模式,像这样:

search = r'\b' + re.escape('Sortes\index[persons]{Sortes}') + r'\b'
match = 'test Sortes\index[persons]{Sortes} text'
re.search(search, match)
Run Code Online (Sandbox Code Playgroud)

现在,我没有得到匹配。

如果搜索模式不包含任何字符[]{},则它有效。例如:

>>> re.search(r'\b' + re.escape('Sortes\index') + r'\b', 'test Sortes\index test')
<_sre.SRE_Match object; span=(5, 17), match='Sortes\\index'>
Run Code Online (Sandbox Code Playgroud)

另外,如果我删除 …

python regex

7
推荐指数
1
解决办法
1067
查看次数

标签 统计

regex ×2

javascript ×1

python ×1