This article introduces how to match cross-lines when using regular expressions in PowerShell.
It is a very common operation to use regular expressions to match search strings in PowerShell. But if you encounter a string with multiple lines, the regular regular expression will not work properly.
If you don't believe it, please read:
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "1111`n2222" -match "^1.*2$"
False
PS C:\Users\spaybow> "1111`n2222" -match "1.*2"
False
The above two return values are False, which is very confusing. If you remove the "`n" in "1111`n2222", the above two sentences will return True.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "11112222" -match "1.*2"
True
PS C:\Users\spaybow> "11112222" -match "^1.*2$"
True
So, how to deal with this kind of regular expression matching that requires cross-row? The answer is to use the (?S) option, prepend the regular expression with "(?s)" so that the regular expression can match across rows.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "1111`n2222" -match "(?s)^1.*2$"
True
PS C:\Users\spaybow> "1111`n2222" -match "(?s)1.*2"
True
This article introduces so much about cross-row matching of regular expressions in PowerShell. I hope it will be helpful to you. Thank you!