Home > database >  Regex to capture a variable number of items?
Regex to capture a variable number of items?

Time:03-29

I am trying to use a regex to capture values from SPACE delimited items. Yes, I know that I could use [string]::Split() or -split. The goal is to use a regex in order fit it into the regex of another, larger regex.

There are a variable number of items in the string. In this example there are four (4). The resulting $Matches variable has the full string for all Value members. I also tried the regex '^((.*)\s*) ', but that resulted in '' for all except the first .\value.txt

How can I write a regex to capture a variable number of items.

PS C:\src\t> $s = 'now is the time'
PS C:\src\t> $m = [regex]::Matches($s, '^((.*)\s*)')
PS C:\src\t> $m

Groups    : {0, 1, 2}
Success   : True
Name      : 0
Captures  : {0}
Index     : 0
Length    : 15
Value     : now is the time
ValueSpan :

PS C:\src\t> $m.Groups.Value
now is the time
now is the time
now is the time
PS C:\src\t> $PSVersionTable.PSVersion.ToString()
7.2.2

CodePudding user response:

I guess the following will work for you

[^\s] 

[^\s] means "not a space"

means 1 or more characters

CodePudding user response:

You can use [regex]::Match() to find the first matching substring, then call NextMatch() to advance through the input string until no further matches can be made.

I've taken the liberty of simplifying the expression to \S (consecutive non-whitespace characters):

$string = 'now is the time'
$regex = [regex]'\S '

$match = $regex.Match($string)
while($match.Success){
  Write-Host "Match at index [$($match.Index)]: '$($match.Value)'"

  # advance to the next match, if any
  $match = $match.NextMatch()
}

Which will print:

Match at index [0]: 'now'
Match at index [4]: 'is'
Match at index [7]: 'the'
Match at index [11]: 'time'
  • Related