多行正则表达式匹配配置块 [英] Multiline regex to match config block
问题描述
我在尝试从文件中匹配某个配置块(多个)时遇到了一些问题.下面是我试图从配置文件中提取的块:
I am having some issues trying to match a certain config block (multiple ones) from a file. Below is the block that I'm trying to extract from the config file:
ap71xx 00-01-23-45-67-89
use profile PROFILE
use rf-domain DOMAIN
hostname ACCESSPOINT
area inside
!
有多个这样的,每个都有不同的 MAC 地址.如何跨多行匹配配置块?
There are multiple ones just like this, each with a different MAC address. How do I match a config block across multiple lines?
推荐答案
您可能遇到的第一个问题是,为了跨多行匹配,您需要将文件内容作为单个字符串处理,而不是逐行处理.例如,如果您使用 Get-Content 读取文件的内容,那么默认情况下它会为您提供一个字符串数组 - 每行一个元素.要跨行匹配您希望文件在单个字符串中(并希望文件不要太大).你可以这样做:
The first problem you may run into is that in order to match across multiple lines, you need to process the file's contents as a single string rather than by individual line. For example, if you use Get-Content to read the contents of the file then by default it will give you an array of strings - one element for each line. To match across lines you want the file in a single string (and hope the file isn't too huge). You can do this like so:
$fileContent = [io.file]::ReadAllText("C:\file.txt")
或者在 PowerShell 3.0 中,您可以使用带有 -Raw
参数的 Get-Content:
Or in PowerShell 3.0 you can use Get-Content with the -Raw
parameter:
$fileContent = Get-Content c:\file.txt -Raw
然后你需要指定一个正则表达式选项来匹配跨行终止符,即
Then you need to specify a regex option to match across line terminators i.e.
- SingleLine 模式(
.
匹配任何字符包括换行符),以及 - 多行模式(
^
和$
匹配嵌入的行终止符),例如 (?smi)
- 注意i"是忽略大小写
- SingleLine mode (
.
matches any char including line feed), as well as - Multiline mode (
^
and$
match embedded line terminators), e.g. (?smi)
- note the "i" is to ignore case
例如:
C:\> $fileContent | Select-String '(?smi)([0-9a-f]{2}(-|\s*$)){6}.*?!' -AllMatches |
Foreach {$_.Matches} | Foreach {$_.Value}
00-01-23-45-67-89
use profile PROFILE
use rf-domain DOMAIN
hostname ACCESSPOINT
area inside
!
00-01-23-45-67-89
use profile PROFILE
use rf-domain DOMAIN
hostname ACCESSPOINT
area inside
!
使用 Select-String
cmdlet 进行搜索,因为您可以指定 -AllMatches
它将输出所有匹配项,而 -match
运算符在第一次匹配后停止.有道理,因为它是一个布尔运算符,只需要确定是否存在 a 匹配.
Use the Select-String
cmdlet to do the search because you can specify -AllMatches
and it will output all matches whereas the -match
operator stops after the first match. Makes sense because it is a Boolean operator that just needs to determine if there is a match.
这篇关于多行正则表达式匹配配置块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!