如何在还包含字母的字符串中增加数字?

时间:2019-10-29 06:59:36

标签: regex powershell replace

我想对字符串中的数字执行算术运算。

例如:const getEmployeeStartLeave = value => { let employeeLeaves = [...isEmployeeLeave]; const calendarDates = value.toString(); const formatCalendarDates = moment(calendarDates).format('YYYY-MM-DD'); const filteredData = [].concat .apply([], employeeLeaves) .filter(item => item.startDate === formatCalendarDates); return filteredData; }; 应该变成SGJKR67

另一个:SGJKR68应该变成NYSC34

仅数字更改,在此示例中,两个数字均增加一个。

3 个答案:

答案 0 :(得分:1)

使用正则表达式和捕获组可以解决您的问题:

$reg = [regex]::new("([A-Z]+)(\d+)")
$m = $reg.Match("SGJKR67")
$digits = $m.Groups[2] # will be 67
$digits = $digit + 1; # or apply anything you want
$result = "$($m.Groups[1])$digits" # will be SGJKR and 68.

您将有3组符合您的比赛条件:

  • 整个“单词”。
  • 字母
  • 数字。

答案 1 :(得分:1)

在PowerShell Core (v6.1 +)中,您可以使用-replace operator

PS> 'SGJKR67', 'NYSC34' -replace '\d+', { 1 + [int] $_.Value }

SGJKR68
NYSC35

在不支持脚本块替换操作数的 Windows PowerShell 中,必须使用.NET [regex]类型的静态.Replace() method直接:

PS> 'SGJKR67', 'NYSC34' | ForEach-Object {
      [regex]::Replace($_, '\d+', { param($m) 1 + [int] $m.Value })
    }

SGJKR68
NYSC35

注意:与-replace不同,[regex]::Match()不支持传递输入字符串的 array ,因此使用ForEach-Object调用;在 脚本块({ ... }中,$_指的是手边的输入字符串

除了在手边的匹配([System.Text.RegularExpressions.Match]实例)作为 argument 传递到脚本块(其参数声明为param($m))之外,方法基本相同。捕获变量$m

答案 2 :(得分:0)

您必须将数字与字符串分开,计算新数字并将所有内容返回为字符串。

[System.String]$NumberInString = 'SGJKR68'
[System.String]$String = $NumberInString.Substring(0, 5)
[System.Int32]$Int = $NumberInString.Substring(5, 2)
$Int += 1
[System.String]$NewNumberInString = ($String + $Int)
$NewNumberInString