我有一個看起來像這樣的宣告:
DO prog3 WHILE prog1 arg1 arg2 <= prog2 arg1 END
我想使用 grep 樣式的正則運算式從陳述句中提取引數prog3, prog1 arg1 arg2, <=(可以是任何運算子) 。prog2 arg1
我的命令是:
grep -E 'DO(.*)WHILE(.*)[<=](.*)END' <<< \
'DO prog3 WHILE prog1 arg1 arg2 <= prog2 arg1 END' -o
正則運算式適用于 regex101.com,但不適用于 grep,它只是將整個陳述句作為匹配項回傳,即
DO prog3 WHILE prog1 arg1 arg2 <= prog2 arg1 END
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
使用perl單線,您可以嘗試以下代碼。僅使用您展示的樣本進行撰寫和測驗。這是Perl 程式中使用的正則運算式的在線演示。
perl -pe 's/\bDO (.*?) WHILE ([^=><]*) ([=><] ) (.*?)\bEND\b/$1\n$2\n$3\n$4/' Input_file
輸出如下:
prog3
prog1 arg1 arg2
<=
prog2 arg1
說明:為上述使用的正則運算式添加詳細說明。
\bDO ##Matching word boundary followed by DO here.
(.*?) ##Creating 1st capturing group putting a lazy match to get values just before next mentioned value.
WHILE ##Matching space followed by WHILE.
([^=><]*) ##Matching space and creating 2nd capturing group which matches anything apart from = < >
([=><] ) ##Matching space and creating 3rd capturing group where matching 1 or more occurrences of > < OR =
(.*?) ##Matching space and creating 4th capturing group with a Lazy match in it.
\bEND\b ##Matching word boundary followed by END followed by another word boundary here.
uj5u.com熱心網友回復:
grep不輸出所有捕獲組。像這樣使用會更好sed:
s='DO prog3 WHILE prog1 arg1 arg2 <= prog2 arg1 END'
sed -E 's/DO (.*) WHILE (.*) ([<>=] ) (.*) END/\1\n\2\n\3\n\4/' <<< "$s"
prog3
prog1 arg1 arg2
<=
prog2 arg1
這里:
[<>=]在單獨的捕獲組中用于抓取操作員文本- 使用捕獲組周圍的空間來處理貪婪
.* - 在每個反向參考之后使用
\n以在單獨的行上列印每個組,例如grep -o
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/512183.html
標籤:正则表达式解析grep
上一篇:可以獲得實際的代幣價值嗎?
下一篇:從自定義XBRL檔案設定背景關系
