首页 > 解决方案 > 如何在 R 中使用 /x 正则表达式选项

问题描述

更新:

把这个留在这里是为了琐事,但重复问题的答案要漂亮得多。

我想通过使用该/x选项在 R 中很好地格式化我的正则表达式。我知道这是一个 PCRE 选项,所以我通过perl=TRUE启用该语言样式。

但是正则表达式没有返回任何匹配项。没有编译错误,但没有匹配。

这是我的测试代码:

expr <- "# match any year
([0-9]{4})
(
  # January-September
  (?:0[1-9])
  # OR October - December
  |(?:1[0-2])
)
(
  # First nine days of the month.
  (?:0[1-9])
  # Next twenty days of the month.
  |(?:[1-2][0-9])
  # Last two days of the month.
  |(?:(?<!02)3[0-1])
)
# A hyphen and then any four digits.
-([0-9]{4})/x"

print(
  grep(
    expr, 
    c(
      "20190916-9999",
      "20041009-1234",
      "19981231-4321",
      "20420230-0000"
    ),
    perl=TRUE,
    value=TRUE
  )
)

前三个字符串应该匹配,但第四个不应该。

任何指导将不胜感激!

标签: rregexpcre

解决方案


看来我可以像这样构建一个带注释的正则表达式:

expr <- "(?# 
# match any year
)([0-9]{4})(?#
)(?#
  # January-September
  )((?:0[1-9])(?#
  # OR October - December
  )|(?:1[0-2])(?#
))(?#
  # First nine days of the month.
  )((?:0[1-9])(?#
  # Next twenty days of the month.
  )|(?:[1-2][0-9])(?#
  # Last two days of the month.
  )|(?:(?<!02)3[0-1])(?#
))(?#
# A hyphen and then any four digits.
)-([0-9]{4})"

print(
  grep(
    expr, 
    c(
      "20190916-9999",
      "20041009-1234",
      "19981231-4321",
      "20420230-0000"
    ),
    perl=TRUE,
    value=TRUE
  )
)

括号令人生畏,但它可能仍然比零空白正则表达式更好。感谢您的提示,GKi!


推荐阅读