gpt4 book ai didi

ruby - 构建正则表达式以仅匹配 2 个单词

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:47 24 4
gpt4 key购买 nike

我正在尝试使正则表达式只匹配 2 个单词和一个单一的步调。没有特殊符号,只有 [a-zA-Z] 空格 [a-zA-z]

Foo Bar      # Match    (two words and one space only)
Foo # Mismatch (only one word)
Foo Bar # Mismatch (2 spaces)
Foo Bar Baz # Mismatch (3 words)

最佳答案

你想要 ^[a-zA-Z]+\s[a-zA-Z]+$

^   # Matches the start of the string
+ # quantifier mean one or more of the previous character class
\s # matches whitespace characters
$ # Matches the end of the string

anchor ^$ 在这里很重要。

Demo :

if "foo bar" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/ 
print "match 1"
end
if "foo bar" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/
print "match 2"
end
if "foo bar biz" =~ /^[a-zA-Z]+\s[a-zA-Z]+$/
print "match 3"
end

输出:

Match 1

关于ruby - 构建正则表达式以仅匹配 2 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14154263/

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