正则表达式提取变量子串

时间:2015-08-17 16:21:36

标签: regex substring

我真的试图自己解决这个问题,但是我一直在用这一块砖头撞墙。

我有一个包含许多行的文件: -

<outputColumn id="426" name="Net Salary per month € (3rd Applicant)" description="" lineageId="426" precision="0" scale="0" length="255" dataType="wstr" codePage="0" sortKeyPosition="0" comparisonFlags="0" specialFlags="0" errorOrTruncationOperation="Conversion" errorRowDisposition="FailComponent" truncationRowDisposition="FailComponent" externalMetadataColumnId="425" mappedColumnId="0"/>

我想要一个regexp只返回name =“和next”

之间的字符串

在这种情况下,它是'每月净薪水'(第三申请人)'但它可以是任何东西。这就是我通过提取变量子串的意思。

提前致谢。

4 个答案:

答案 0 :(得分:1)

(?<=name=")[^"]*

这应该为你做。参见演示。

https://regex101.com/r/uF4oY4/50

如果您没有lookarounds,请使用

name="([^"]*)

并抓住group 1

答案 1 :(得分:1)

这可能会有所帮助: 正则表达式= name="(.*?)"

<强>样本

https://regex101.com/r/uF4oY4/51

如果有帮助,请告诉我。

答案 2 :(得分:0)

因为有很多&#39;&#39;&#39;你可能不得不使用 lazy flag

之后的字符

^.*name=\"(.+?)\".*$

匹配整行,并且应该在组(.+?)

中提供您想要的内容

答案 3 :(得分:0)

现有答案中有有用的正则表达式;与-replace operator一起使用可以让您通过单个操作

提取感兴趣的信息:

$line = '<outputColumn id="426" name="Net Salary per month € (3rd Applicant)" description="" lineageId="426" precision="0" scale="0" length="255" dataType="wstr" codePage="0" sortKeyPosition="0" comparisonFlags="0" specialFlags="0" errorOrTruncationOperation="Conversion" errorRowDisposition="FailComponent" truncationRowDisposition="FailComponent" externalMetadataColumnId="425" mappedColumnId="0"/>'

# Extract the "name" attribute value.
# Note how the regex is designed to match the *full line*, which is then
# replaced with what the first (and only) capture group, (...), matched, $1
$line -replace '^.+ name="([^"]*).+', '$1'

这将输出具有逐字内容Net Salary per month € (3rd Applicant)的字符串。


退后一步:您的示例行是有效的XML元素,始终最好使用专用的XML解析器。

每行解析为XML会很慢,但是也许您可以解析整个文件,它使用XML DOM的PowerShell's property-based adaption提供了一种简单的解决方案,通过[xml]类型(System.Xml.XmlDocument):

$fileContent = @'
<xml>
<outputColumn id="426" name="Net Salary per month € (3rd Applicant)" description="" lineageId="426" precision="0" scale="0" length="255" dataType="wstr" codePage="0" sortKeyPosition="0" comparisonFlags="0" specialFlags="0" errorOrTruncationOperation="Conversion" errorRowDisposition="FailComponent" truncationRowDisposition="FailComponent" externalMetadataColumnId="425" mappedColumnId="0"/>
<outputColumn id="427" name="Net Salary per month € (4th Applicant)" description="" lineageId="426" precision="0" scale="0" length="255" dataType="wstr" codePage="0" sortKeyPosition="0" comparisonFlags="0" specialFlags="0" errorOrTruncationOperation="Conversion" errorRowDisposition="FailComponent" truncationRowDisposition="FailComponent" externalMetadataColumnId="425" mappedColumnId="0"/>
</xml>
'@

([xml] $fileContent).xml.outputColumn.name

上面的方法在所有"name"元素上产生了<outputColumn>属性值:

Net Salary per month € (3rd Applicant)
Net Salary per month € (4th Applicant)