gpt4 book ai didi

用于查找单词的 Ruby 正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:51 27 4
gpt4 key购买 nike

我对正则表达式很陌生。我正在使用正则表达式:

/\w+/

要检查单词,很明显这会出现标点符号问题,但我不太确定如何更改此正则表达式。例如,当我从我创建的类中运行此命令时:

Wordify.new.regex(/\w+/).string("This sentence isn't 'the best-example, isn't it not?...").display

我得到输出:

-----------
this: 1
sentence: 1
isn: 2
t: 2
the: 1
best: 1
example: 1
it: 1
not: 1
-----------

如何调整正则表达式,使其匹配带撇号的单词,例如:不是作为一个单词,但在搜索时只会匹配the>'thethe'。像 stack-overflow 这样的单词中间的连字符应该分别匹配 return stackoverflow,这已经做到了。

此外,单词不能以数字开头或结尾,例如 test1241436test 应该变成 test,但是 te7st 没问题。不应识别纯数字。

抱歉,我知道这是一个很大的问题,但我不确定从哪里开始使用正则表达式。如果可能的话,您还可以解释一下该表达式的含义,我们将不胜感激。

最佳答案

str = "This is 2a' 4test' of my agréable re4'gex, n'est-ce pas?"

r = /
[[:alpha:]] # match a letter
(?: # begin the outer non-capture group
(?:[[:alpha:]]|\d|') # match a letter, digit or apostrophe in a non-capture group
* # execute the above non-capture group zero or more times
[[:alpha:]] # match a letter
)? # close the outer non-capture group and make it optional
/x # free-spacing regex definition mode

str.scan r
#=> ["This", "is", "a", "test", "of", "my", "agréable", "re4'gex", "n'est", "ce", "pas"]

请注意,如果要匹配的字符串是单个字符,则需要外部捕获组。

嗯。也许我们应该在内部非捕获组中添加一个连字符。

r = /[[:alpha:]](?:(?:[[:alpha:]]|\d|'|-)*[[:alpha:]])?/
str.scan r
#=> ["This", "is", "a", "test", "of", "my", "agréable", "re4'gex", "n'est-ce", "pas"]

我现在很少用到单词匹配字符\w,主要是因为它匹配下划线,还有字母和数字。相反,我伸手去拿 POSIX bracket expression (搜索“POSIX”),它有一个额外的(也许是主要的)好处,即它不是以英语为中心的。例如,匹配除下划线以外的单词字符是 [[:alnum:]]

关于用于查找单词的 Ruby 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836499/

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