我正在尝试从字符串中选择一个数字。数字长度可以在5到10个字符之间。例如,我有两个要从字符串中提取的作业号。
"job number:45678 date:01/01/16" # => jobnumber = "45678"
"job number:123421312 date:03/03/16" # => jobnumber = "123421312"
答案 0 :(得分:2)
r = /(?<=\Ajob number:)\d{5,10}(?!\d)/
"job number:45678 date:01/01/16"[r]
#=> "45678"
"job number:4567 date:01/01/16"[r]
#=> nil
"job number:0123456789 date:01/01/16"[r]
#=> "0123456789"
"job number:01234567891 date:01/01/16"[r]
#=> nil
(?<=\Ajob number:)
是一个肯定的后瞻,它要求字符串'job number:'位于字符串的开头(\A
),但该字符串不是其中的一部分比赛\d{5,10}
匹配5-10位数字(?!\d)
是否定前瞻,可确保匹配后面没有数字。如果没有这个,我上面的上一个例子将返回0123456789
。答案 1 :(得分:1)
str = 'job number:45678 date:01/01/16'
regex = %r{
\A #Match start of string, followed by...
job[ ]number: #the literal string "job number:", followed by...
(\d{5,10}) #a digit, 5 or more times--but not more than 10 times, captured in group 1.
}xm #Flags: Ignore whitespace in regex. Dot matches \n.
puts str[regex, 1] #Return group 1 of match.
--output:--
45678
答案 2 :(得分:-1)
看起来像这样:
"job number:45678 date:01/01/16"[/\d+/]
=> "45678"
"job number:123421312 date:03/03/16"[/\d+/]
=> "123421312"
答案 3 :(得分:-2)
找到我要找的东西
/ ^ [A-ZA-Z] {5,10} $ /