我有兩個正則表達式值,我試圖合併成一個語句,但它不能正常工作。我需要能夠顯示其中有註釋的行,或者以空格開始,然後發表評論。結合這兩個正則表達式
即。
/* comment
/* comment
sed -n "/\(^[/*]\).*\([*/]$\)/ p" testfile
sed -n "/^\s/ p" testfile
我一直在嘗試使用|聲明,但它不起作用。
是否有可能將它們合併爲一個或我需要單獨運行它們。
感謝
我有兩個正則表達式值,我試圖合併成一個語句,但它不能正常工作。我需要能夠顯示其中有註釋的行,或者以空格開始,然後發表評論。結合這兩個正則表達式
即。
/* comment
/* comment
sed -n "/\(^[/*]\).*\([*/]$\)/ p" testfile
sed -n "/^\s/ p" testfile
我一直在嘗試使用|聲明,但它不起作用。
是否有可能將它們合併爲一個或我需要單獨運行它們。
感謝
應涵蓋這兩種情況下
/^\s*\/\*.*/
你可以試試:
/^[ ]*(\/\*.*)$/
正則表達式上面會匹配任何意見的線條,可以用空格開始,並將該行捕獲到一個組中。檢查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
至於其他的答案說明,它往往可能找到一個正則表達式一般足以滿足您的一切原始表達式匹配。事實上,這始終是可能的,因爲你總是可以將兩個表達式是這樣的:(根據您使用的話,你可能需要使用反斜槓)
(regex_1|regex_2|...|regex_n)
然而,sed
程序可能包括若干語句,所以你的例子可以簡單地改寫爲:
sed -n "/\(^[/*]\).*\([*/]$\)/p /^\s/p" testfile
您可以使用grep:
grep "^ */\*" testfile
^=行 一開始* I s重複空間0次或更多次 第二顆星逃脫,所以這是一個真正的。
你想在C程序或其他東西中找到評論嗎?您的問題包括簡潔,可測試的樣本輸入和預期輸出。包括很難正確的情況,例如'/ *'出現在字符串中。 –