gpt4 book ai didi

正则表达式等价

转载 作者:太空宇宙 更新时间:2023-11-04 00:41:50 25 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来实现与 grep -w 相同的结果。

我现在想到的是:

var regex = /([^\w]|^)word_to_search([^\w]|$)/;

它似乎工作正常。

您知道有“更好”的解决方案吗?

最佳答案

使用单词边界应该更简单,相当于 grep -w:

/\bword_to_search\b/

根据man grep:

-w, --word-regexp
Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.

关于正则表达式等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36352806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com