【问题标题】:How to evaluate math expression in matched result of a regular expression in Powershell?如何评估Powershell中正则表达式匹配结果中的数学表达式?
【发布时间】:2021-11-12 05:06:29
【问题描述】:

我有一个关于正则表达式的问题。我想知道是否可以在powershell中对正则表达式的匹配结果评估数学表达式?我不能使用 powershell 来评估它,只需要正则表达式。

问题陈述:

我有如下代码:

$id = $reader.GetValue(0).ToString();
$col1 = $reader.GetValue(1).ToString();
$col2 = $reader.GetValue(2).ToString();
$col3 = $reader.GetValue(3).ToString();
$col4 = $reader.GetValue(4).ToString();
$col5 = $reader.GetValue(5).ToString();
$col6 = $reader.GetValue(6).ToString();
$col7 = $reader.GetValue(7).ToString();
...

我需要使用 Powershell ISE 的查找和替换对话框在 GetValue() 文本中增加 3 个索引 0、1、2 等。

结果应该是这样的:

$id = $reader.GetValue(3).ToString();
$col1 = $reader.GetValue(4).ToString();
$col2 = $reader.GetValue(5).ToString();
$col3 = $reader.GetValue(6).ToString();
$col4 = $reader.GetValue(7).ToString();
$col5 = $reader.GetValue(8).ToString();
$col6 = $reader.GetValue(9).ToString();
$col7 = $reader.GetValue(10).ToString();
...

我试过

Find what: GetValue\((\d)\)
Replace with: GetValue($1+3)

但我没能成功,我找不到任何文件或关于该问题的合理解决方案。

非常感谢您提供任何可能的解决方案。

【问题讨论】:

  • 重构你的代码,在左边使用一个数组和一个循环,你不需要做花哨的正则表达式来改变起始索引
  • 关于解析数学中缀表示法,请参阅前面的q&a
  • 下面的答案有帮助吗?如果您需要更多帮助,请告知。
  • 不幸的是,这不能满足我的问题,因为我想用正则表达式来做。实际上,我正在寻找“仅”正则表达式(在“替换为”部分)是否可能的答案。如果有什么办法。我也找不到解决办法。
  • 您使用的是哪个代码编辑器?

标签: regex powershell


【解决方案1】:

你可以使用

PS> $s = '$col1 = $reader.GetValue(1).ToString();'
PS> $rx = [regex]'(?<=GetValue\()\d+(?=\))'
PS> $rx.Replace($s, { param($m) [int]$m.Value + 1 })
$col1 = $reader.GetValue(2).ToString();

详情

  • 这里将正则表达式模式编译为正则表达式对象
  • 模式被重写为只消耗一个或多个数字,其余的被非消耗的环视包裹((?&lt;=GetValue\() 是正向的后视,(?=\)) 是正向的前瞻),以便进一步的匹配操作可以更简单
  • 使用带有匹配评估器的Regex.Replace方法,{ param($m) [int]$m.Value + 1 }部分取匹配值(\d+匹配的内容),将字符串转换为整数值,添加1并将结果放回消耗的数字。

请参阅regex demo详情

  • (?&lt;=GetValue\() - 紧靠当前位置左侧,必须有GetValue(文字
  • \d+ - 一位或多位数字
  • (?=\)) - 在当前位置的右侧,必须有一个 ) 字符。

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    相关资源
    最近更新 更多