Powershell正则表达式匹配开始和结束字符串不匹配?

时间:2022-05-19 21:43:56

I am attempting to match the following string, it always
begins with Removing:
and ends with --- For User:

我试图匹配以下字符串,它始终以删除开头:并以---用户结束:

I tried using the following regex:

我尝试使用以下正则表达式:

\bRemoving: \w+\ --- For User: \b

Removing: Random_Group_Here --- For User: - Should Match This

删除:Random_Group_Here ---对于用户: - 应匹配此项

I'm trying to assign this regex to a powershell variable that I can use for a -replace string.

我正在尝试将此正则表达式赋给一个powershell变量,我可以将其用于-replace字符串。

$regex = "\[\bRemoving: \w+\ --- For User: \b\]"

1 个解决方案

#1


2  

The last \b word boundary only matches if there is a word char (i.e. mostly a letter, digit, _) after the space at the end of the pattern. Since there is no such a char, the last word boundary prevents from matching.

如果在模式结尾处的空格之后存在单词char(即,主要是字母,数字,_),则最后的\ b字边界仅匹配。由于没有这样的字符,最后一个字边界阻止匹配。

Either remove the last \b, or - if you want to only match that space when not followed with a word char - with (?!\w) negative lookahead that will check just that.

要么删除最后一个\ b,要么 - 如果你只想匹配那个没有跟着单词char的空格 - 用(?!\ w)否定前瞻来检查那个。

You may also replace literal spaces with \s* (0+ whitespaces) / \s+ (1+ whitespaces) patterns to match any kind and any amount of whitespace between specific chars.

您还可以使用\ s *(0+空格)/ \ s +(1+空格)模式替换文字空间,以匹配特定字符之间的任何种类和任何数量的空白。

Here is a variation:

这是一个变化:

\bRemoving:\s*\w+\s*---\s*For\s+User:\s*

See the regex demo.

请参阅正则表达式演示。

#1


2  

The last \b word boundary only matches if there is a word char (i.e. mostly a letter, digit, _) after the space at the end of the pattern. Since there is no such a char, the last word boundary prevents from matching.

如果在模式结尾处的空格之后存在单词char(即,主要是字母,数字,_),则最后的\ b字边界仅匹配。由于没有这样的字符,最后一个字边界阻止匹配。

Either remove the last \b, or - if you want to only match that space when not followed with a word char - with (?!\w) negative lookahead that will check just that.

要么删除最后一个\ b,要么 - 如果你只想匹配那个没有跟着单词char的空格 - 用(?!\ w)否定前瞻来检查那个。

You may also replace literal spaces with \s* (0+ whitespaces) / \s+ (1+ whitespaces) patterns to match any kind and any amount of whitespace between specific chars.

您还可以使用\ s *(0+空格)/ \ s +(1+空格)模式替换文字空间,以匹配特定字符之间的任何种类和任何数量的空白。

Here is a variation:

这是一个变化:

\bRemoving:\s*\w+\s*---\s*For\s+User:\s*

See the regex demo.

请参阅正则表达式演示。