带有重复的简单正则表达式让我难住了
问候。
这么简单的问题却难倒了我。这里的人非常乐于助人。
我正在尝试匹配包含一些固定文本和随机数字的字符串。
echo blah blah abc123 | grep -o abc
abc
echo blah blah abc123 | grep -o abc[0-9]
abc1
echo blah blah abc123 | grep -o abc[0-9]+
echo blah blah abc123 | grep -o "abc[0-9]+"
echo blah blah abc123 | grep -o "abc[0-9]*"
abc123
echo blah blah abc123 | grep -o abc[0-9]{3}
echo blah blah abc123 | grep -o "abc[0-9]{3}"
* 运算符(匹配零次或多次)是唯一能按我的预期工作的运算符。
为什么 + 运算符(匹配 1 次或多次)不匹配?
为什么特定的重复计数运算符 {3} 不匹配?
如果有影响的话,我正在 Ubuntu 10.10 下的 bash shell 中运行这些示例。
非常感谢。
Greetings.
So simple a problem has me stumped. People here are so helpful.
I am trying to match a string containing some fixed text and random digits.
echo blah blah abc123 | grep -o abc
abc
echo blah blah abc123 | grep -o abc[0-9]
abc1
echo blah blah abc123 | grep -o abc[0-9]+
echo blah blah abc123 | grep -o "abc[0-9]+"
echo blah blah abc123 | grep -o "abc[0-9]*"
abc123
echo blah blah abc123 | grep -o abc[0-9]{3}
echo blah blah abc123 | grep -o "abc[0-9]{3}"
The * operator (matches zero or more times) is the only one that works as I would expect.
Why does the + operator (match 1 or more times) not match?
Why does the specific repetition count operator {3} not match?
I am running these examples in a bash shell under Ubuntu 10.10 if it makes a difference.
Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您转义特殊字符时,它们都会起作用:
未转义,正则表达式正在寻找文字
+
或{
,正如您可能已经推断出的那样。至于为什么必须保持
*
不转义,但必须转义+
,我不确定。They both work when you escape the special characters:
Unescaped, the regex is looking for a literal
+
or{
, as you have probably deduced.As to exactly why you have to keep a
*
unescaped but you have to escape a+
, I'm not sure.