正则表达式不起作用

时间:2016-09-10 03:35:29

标签: ruby regex

我正在研究正则表达式。

id: 1 food: apple, banana
id: 2 food: orange
ids: 3 food: apple, banana
id: 4 food: hello, yellow
id: 5food: apple, banana
id:6 food: ,,,yellow

这是我的正则表达式代码:

    pattern = /id[:] [[:digit:]]+ food[:] [a-z,]+/

id: 1 food: apple, banana
id: 2 food: orange
id: 4 food: hello, yellow
id: 6 food:,,,yellow

此表达式能够使除最后一行之外的所有内容无效。不应打印列表中的最后一行。如何检测到某些东西不是以开始的,

编辑:只允许一个空格

3 个答案:

答案 0 :(得分:1)

^id:\s+[0-9]+\s+food:\s+[a-z,\s]+$

这是我用来匹配id 1,2和4的表达式。

请参阅rubular此处

答案 1 :(得分:1)

▶ input.scan /^id:\s+\d+\s+food:\s+(?:[a-z]+(?:,\s)?)+$/
#⇒ [
#  [0] "id: 1 food: apple, banana",
#  [1] "id: 2 food: orange",
#  [2] "id: 4 food: hello, yellow"
# ]

答案 2 :(得分:1)

我知道不允许使用多个连续的空格。

r = /
    ^                   # match beginning of line
    id:\s               # match "id:" followed by a space
    \d+\s               # match > 0 digits followed by a space
    food:\s             # match "food:" followed by a space
    [[:alpha:]]+        # match > 0 letters
    (?:,\s[[:alpha:]]+) # match comma, space, > 0 letters in a non-capture group
    *                   # perform match on above non-capture group >= 0 times
    $                   # match end of string
    /x                  # free-spacing regex definition mode

str =<<_
id: 1 food: apple, banana
id: 2 food: orange
ids: 3 food: apple, banana
id: 4 food: hello, yellow
id: 5food: apple, banana
id:6 food: ,,,yellow
_

str.scan(r)
  #=> ["id: 1 food: apple, banana",
  #    "id: 2 food: orange",
  #    "id: 4 food: hello, yellow"]