我使用以下grep查询来查找VB源文件中的函数的出现.
grep -nri "^\s*\(public\|private\|protected\)\s*\(sub\|function\)" formName.frm
Run Code Online (Sandbox Code Playgroud)
匹配 -
Private Sub Form_Unload(Cancel As Integer)
Private Sub lbSelect_Click()
...
Run Code Online (Sandbox Code Playgroud)
然而,它错过了像 -
Private Static Sub SaveCustomer()
Run Code Online (Sandbox Code Playgroud)
因为那里附加了"静态"字样.如何在grep查询中考虑这个"可选"字?
Fat*_*ror 18
你可以用a \?
做一些可选的东西:
grep -nri "^\s*\(public\|private\|protected\)\s*\(static\)\?\s*\(sub\|function\)" formName.frm
Run Code Online (Sandbox Code Playgroud)
在这种情况下,包含字符串"static"的前一组是可选的(即可以发生0或1次).
使用grep时,基数明智:
* : 0 or many
+ : 1 or many
? : 0 or 1 <--- this is what you need.
Run Code Online (Sandbox Code Playgroud)
考虑下面的例子(其中非常字代表了你的静态):
I am well
I was well
You are well
You were well
I am very well
He is well
He was well
She is well
She was well
She was very well
Run Code Online (Sandbox Code Playgroud)
如果我们只想要
I am well
I was well
You are well
You were well
I am very well
Run Code Online (Sandbox Code Playgroud)
我们会用'?' (还要注意在"非常"之后仔细放置空格,我们要求'非常'字为零或一次:
egrep "(I|You) (am|was|are|were) (very )?well" file.txt
Run Code Online (Sandbox Code Playgroud)
正如你猜测的那样,我邀请你使用egrep而不是grep(你可以尝试grep -E,用于扩展正则表达式).