【问题标题】:Combine these two regex patterns结合这两种正则表达式模式
【发布时间】:2016-05-15 02:27:35
【问题描述】:
我有两个正则表达式值,我一直在尝试将它们组合成一个语句,但是它不能正常工作。我需要能够显示其中包含 cmets 的行或以空格开头然后包含 cmets。
即。
/* comment
/* comment
sed -n "/\(^[/*]\).*\([*/]$\)/ p" testfile
sed -n "/^\s/ p" testfile
我一直在尝试使用 |声明但是它不起作用。
是否可以将它们合并为一个,或者我需要单独运行它们。
谢谢
【问题讨论】:
-
您是要在 C 程序或其他程序中查找 cmets 吗? edit 您的问题包括简洁、可测试的样本输入和预期输出。包括难以正确处理的情况,例如/* 出现在字符串中。
标签:
regex
linux
shell
sed
【解决方案2】:
你可以试试:
/^[ ]*(\/\*.*)$/
上面的正则表达式将匹配任何带有 cmets 的行,可以以空格开头,并将该行捕获到一个组中。检查Regex Demo
正则表达式解释
/^[ ]*(\/\*.*)$/
^ assert position at start of a line
[ ]* match a single character present in the list below
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
the literal character
1st Capturing group (\/\*.*)
\/ matches the character / literally
\* matches the character * literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of a line
【解决方案3】:
正如其他答案所示,通常可以找到一个足够通用的正则表达式来匹配原始表达式匹配的所有内容。事实上,这总是可能的,因为你总是可以像这样组合两个表达式:
(regex_1|regex_2|...|regex_n)
(根据您使用的方言,您可能必须使用反斜杠。)但是,sed 程序可能包含多个语句,因此您的示例可以简单地重写为:
sed -n "/\(^[/*]\).*\([*/]$\)/p /^\s/p" testfile
【解决方案4】:
你可以使用grep:
grep "^ */\*" testfile
^=行首
第一个 * 重复空格 0 次或更多次
第二颗星被逃脱了,所以那是一颗真实的。