RegEx целевая замена на именованные захваты - PullRequest
0 голосов
/ 30 марта 2019

Дано

$line = '{initError-[cf][3]}_Invalid nodes(s): [3]'

Я могу использовать

$line -match '^\{(?<type>[a-z]+)(-\[(?<target>(C|F|CF))\])?(\[(?<tab>\d+)\])?\}_(?<string>.*)'

И $matches['tab'] будут правильно иметь значение 3. Однако, если я затем захочу увеличить это значение, не затрагивая также [3] в разделе строк, все усложняется. Я могу использовать $tabIndex = $line.indexOf("[$tab]"), чтобы получить индекс первого вхождения, и я также могу использовать $newLine = ([regex]"\[$tab\]").Replace($line, '[4]', 1), чтобы заменить только первое вхождение. Но мне интересно, есть ли способ получить к этому более прямо? В этом нет особой необходимости, так как я когда-нибудь захочу заменить вещи внутри начального {} _, который имеет очень непротиворечивую форму, поэтому замена первого экземпляра работает, просто интересно, упускаю ли я более элегантное решение, которое также может понадобиться в другой ситуации.

Ответы [ 2 ]

0 голосов
/ 30 марта 2019

Альтернативный способ увеличения первого числа в скобках - использование оператора -Split для доступа к номеру, который вы хотите изменить:

$line = '{initError-[cf][3]}_Invalid nodes(s): [3]'
$NewLine = $line -split "(\d+)"
$NewLine[1] = [int]$newLine[1] + 1
-join $NewLine

Выход:

{initError-[cf][4]}_Invalid nodes(s): [3]
0 голосов
/ 30 марта 2019

Я бы немного изменил регулярное выражение, потому что смешивать именованные захваты с нумерованными захватами не рекомендуется, поэтому оно становится таким:

'^\{(?<type>[a-z]+)(?:-\[(?<target>[CF]{1,2})\])?(?:\[(?<tab>\d+)\])?\}_(?<string>.*)'

Затем вы можете использовать его, как показано ниже, для замены значения tab:

$line        = '{initError-[cf][3]}_Invalid nodes(s): [3]'
$newTabValue = 12345

$line -replace '^\{(?<type>[a-z]+)(?:-\[(?<target>[CF]{1,2})\])?(?:\[(?<tab>\d+)\])?\}_(?<string>.*)', "{`${type}-[`${target}][$newTabValue]}_`${string}"

Результатом будет:

{initError-[cf][12345]}_Invalid nodes(s): [3]

Детали регулярного выражения:

^                    Assert position at the beginning of the string
\{                   Match the character “{” literally
(?<type>             Match the regular expression below and capture its match into backreference with name “type”
   [a-z]             Match a single character in the range between “a” and “z”
      +              Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?:                  Match the regular expression below
   -                 Match the character “-” literally
   \[                Match the character “[” literally
   (?<target>        Match the regular expression below and capture its match into backreference with name “target”
      [CF]           Match a single character present in the list “CF”
         {1,2}       Between one and 2 times, as many times as possible, giving back as needed (greedy)
   )
   \]                Match the character “]” literally
)?                   Between zero and one times, as many times as possible, giving back as needed (greedy)
(?:                  Match the regular expression below
   \[                Match the character “[” literally
   (?<tab>           Match the regular expression below and capture its match into backreference with name “tab”
      \d             Match a single digit 0..9
         +           Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   )
   \]                Match the character “]” literally
)?                   Between zero and one times, as many times as possible, giving back as needed (greedy)
\}                   Match the character “}” literally
_                    Match the character “_” literally
(?<string>           Match the regular expression below and capture its match into backreference with name “string”
   .                 Match any single character that is not a line break character
      *              Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...