问题描述
我有一个正则表达式,它对字符串进行搜索并创建两个匹配组:
I have a regex that does a search on a string and creates two match groups:
if ($BASICEDITMESSAGECONTENT -match '(?sm)(^.*?</title>)(.*)')
{
if ($matches.Count -ge 3)
{
$BASICEDITMESSAGECONTENT = "$matches[1]$SCRIPTREFERENCE$matches[2]"
echo $BASICEDITMESSAGECONTENT
...
}
}
当我将其回显时,将得到以下输出:
When I echo it back, I get the following output:
System.Collections.Hashtable[1]<MYSCRIPTREFERENCE>System.Collections.Hashtable[2]
我在字符串中不需要这样的System.Collections.Hashtable
值,我只想从该正则表达式分组中找到匹配文本的实际值字符串.我该如何实现?
I don't want System.Collections.Hashtable
values like this in the string, I just want the actual value string of the matching text from that regex grouping. How can I make it happen?
例如,当我使用echo $matches[1]
时,它将显示正则表达式组的实际值,而不是System.Collections.Hashtable[1]
.
For example, when I use echo $matches[1]
, it displays the actual value of the regular expression group, not System.Collections.Hashtable[1]
.
推荐答案
您需要使用 sub-表达式索引哈希表:
You need to use sub-expressions to index the hashtables:
$BASICEDITMESSAGECONTENT = "$($matches[1])$SCRIPTREFERENCE$($matches[2])"
注意每个索引周围的$(...)
.您希望将字符串文字作为表达式求值的所有部分都放在$(...)
内.否则,PowerShell只会扩展变量名,并将[1]
之类的其他内容视为普通文本.
Notice the $(...)
around each index. All parts of string literals that you want evaluated as expressions need to be placed inside $(...)
. Otherwise, PowerShell will only expand the variable names and treat other stuff like [1]
as just normal text.
这篇关于正则表达式将组匹配到PowerShell中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!