假设我有以下字符串:

str1 = "[1] : blah blah blah"
str2 = "[2] : Something"
str3 = "Nothing"

我编写了一个方法foo(str),它接受一个字符串作为参数,如果字符串以“[数字]”开头,则应该返回true,其中数字可以是任何自然数(1,2,3,4…)。所以str1str2应该返回truestr3应返回false。
我无法找出与"[DIGIT]"匹配的正则表达式/[[\d]]/是我能想到的最好的,它不起作用,只匹配"N]",错过了起始括号试试here
当前方法如下:
def foo(str)
  str =~ /[[\d]]/
end

最佳答案

尝试this,斜线:

$> irb
>> str1 = "[1] : blah blah blah"
>> str1[/\[\d\]/]
=> "[1]"

使用\字符转义正则表达式中具有特殊含义的字符。

关于ruby - 检查字符串在ruby中是否以正则表达式开头以匹配“[NATURAL NUMBER]”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39171703/

10-11 20:21
查看更多