r - 如何在 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
)
)
前三个字符串应该匹配,但第四个不应该。
任何指导将不胜感激!
解决方案
看来我可以像这样构建一个带注释的正则表达式:
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!
推荐阅读
- mp4 - 分析奇特的avcC原子结构
- mongodb - 应用程序错误、heroku 托管、后端应用程序
- python - 找不到 add_intercept 的签名:
- javascript - 通过 React 使用 useState 和 onClick 更改背景图像
- c# - 剃刀页面。路由问题。重定向到另一个页面
- javascript - 对于具有多个会话/房间且每个都使用定时事件的多人游戏来说,正确的设置是什么
- linux - 我的 Linux 中安装了这么多 Python3 包(WSL - Ubuntu)
- python - Python中有没有办法创建用户名和密码菜单,其中用户名和密码通过.txt文件中的信息进行验证?
- ansible - ansible.builtin.copy:: 如何复制多个文件
- html - xampp localhost 没有按原样打开文件