[英]Ruby regex to match a pattern followed by another pattern
I already have a regex to match only single digits in a comma-delimited string. 我已经有一个正则表达式 ,只匹配逗号分隔字符串中的单个数字。 I need to update it to match the strings like following: 我需要更新它以匹配以下字符串:
5|5,4,3
2|1,2 , 3
The constraints are 约束是
the string followed by the pipe character - it should be a single digit in range of 1-7, optionally followed by a comma. 字符串后跟管道字符 - 它应该是1-7范围内的单个数字,可选地后跟逗号。 This pattern can be repetitive. 这种模式可以重复。 For eg following strings are considered to be valid, after the pipe character: 例如,在管道字符之后,以下字符串被认为是有效的:
"6" "1,7" "1,2,3, 4,6" "1, 4,5,7"
However following strings are considered to be invalid 但是,以下字符串被视为无效
"8"
"8, 9,10"
I tried with following (a other variations) 我尝试了以下(其他变化)
\A[1-5]\|[1-7](?=(,|[1-7]))*
but it doesn't work as expected. 但它没有按预期工作。 For eg for sample string 例如用于样品串
5|5,4, 3, 10,5
it just matches 它只是匹配
5|5
I need to capture the digit before pipe character and all the matching digits followed by the pipe character. 我需要捕获管道字符前的数字和所有匹配的数字后跟管道字符。 For eg in following sample string 5|5,4, 3, 2, 1 the regex should capture 例如,在以下样本字符串5 | 5,4,5,2,1中,正则表达式应该捕获
Note: I am using Ruby 2.2.1 注意:我使用的是Ruby 2.2.1
Also do you mind letting me know what mistake I made in my regex pattern which was not making it work as expected? 另外你还介意让我知道我在我的正则表达式模式中犯了什么错误,这个错误没有按预期工作吗?
Thanks. 谢谢。
You could try the below regex. 你可以试试下面的正则表达式。
^([1-5])\|([1-7]\s*(?:,\s*[1-7])*)$
Example: 例:
> "5|5,4, 3, 2, 1".scan(/^([1-5])\|([1-7]\s*(?:,\s*[1-7])*)$/)
=> [["5", "5,4, 3, 2, 1"]]
OR 要么
> "5|5,4, 3, 2, 1".scan(/([1-5])\|([1-7] ?(?:, ?[1-7])*)$/)
=> [["5", "5,4, 3, 2, 1"]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.