正则表达式在计算机编程中相当普遍。但是,它们也可供最终用户使用。例如,如果要使用PowerShell或Findstr命令,则可以使用它们。并且有支持正则表达式的第三方实用程序(例如Agent Ransack和EditPad)。由于它们在许多不同的环境中都非常有用,因此我决定有一个关于它们的提示。

正则表达式是一个字符串,通常由特殊字符组成,旨在匹配搜索模式。例如,如果我们使用Findstr命令,则可以搜索单词“ document”

通过指定搜索字符串“ document [,.]”立即在逗号或句点之后。在这种情况下,特殊字符是方括号,这意味着任何封闭的字符都必须在“文档”一词之后。

正则表达式中可以使用很多特殊字符。下面列出了其中的许多:

Character

Description

Match 0 or more characters. Example: haven matches both heaven

and haven.

+

Match 1 or more characters. Example: he+aven matches heaven and

heeaven but not haven.

^

Match what follows only if it’s at the beginning of the string.

Example: if your regular expression is ^document, it will match document

in the string “document the requirements”, but it will not match

anything in the string “this is a requirements document”.

$

Match what precedes only if it’s at the end of the string.

Example: if your regular expression is document$, it will match document

in the string “this is a requirements document”, but it will not match

anything in the string “document the requirements”.

\d

Match a digit. Example: \d matches each digit individually in

the string “my degree is from 1987”. If you want to match all four

digits at once, just repeat the \d like \d\d\d\d.

.

Match any single character. The period is like a wildcard in that

it will match anything.

(a

b)

要查看正则表达式的作用,让我们结合一些正则表达式,然后使用Findstr命令查找文件中字符串的出现。我有一个名为Barry.tmp的文件,其中包含以下文本:

Video provides a powerful way to help you prove your point.  When you click Online Video, you can paste in the embed code for  the 20 or 30 videos you want to add. You can also type a keyword  to search online for the video that best fits your document.

让我们使用Findstr在文件中查找数字字符串:(请参见图1。)

image

图1.搜索数字字符串。

让我介绍几个其他概念。您可以使用一对方括号来界定要查找的字符范围。例如,指定_ [a-z] _将匹配任何字母字符。同样值得注意的是,您使用反斜杠字符(\)来“转义”后面的字符并按字面意义对待它。如果您要查找否则将被视为正则表达式一部分的字符,则此功能很有用。有了这两条信息,我们现在可以在文件中搜索字母字符,后跟一个句点,即找到句子结尾的行:(请参见图2。)

image

图2.搜索句子的结尾。

最后,请注意:根据我的经验,Windows命令行使用的正则表达式引擎与大多数正则表达式引擎有些不同。应该起作用的正则表达式(以及在其他实用程序中起作用的正则表达式)可能无法按命令行预期的那样工作。因此,知道您的里程可能会有所不同,请尝试一下,但不要打赌您的下一张工资单将确保您输入的内容能够按预期工作。

本技巧(1364)适用于Windows 7、8和10。