Experts, I am stuck. I have a string with various patterns separated by commas. I need to validate two things: (1) that each of patterns matches zero or more of the comma separated strings, and (2) that there are no strings that do not match a pattern. Each string element is/will be separated with a comma (nothing else) and there may be trailing spaces after the commas (which I know I can remove with substitution before the validation step!)
Steps taken so far:
Split string (by comma) into an array of string elements String patterns to match:
(a) single numbers e.g. 1,2,300,5,7,80 (up to 4 digits) etc.
(b) ranges e.g. 1-5, 23-45,45-23 (up to 4 digits either side) etc.
(c) r1-r50, r45-r4 (up to 4 digits)
(d) 1-z, z-100
(e) string which contains one of two patterns 12-34:odd and 34-4:even
What I would like is to pull the groups of pattern matching strings directly into an array through regexp comparison on the original string, rather than splitting it into an array (which does of course work!).
So what regexp(s) would I need to filter for each potential pattern and extract the matching strings elements by looking at the original string?
This is not urgent as I have a working version by splitting them into elements, but as a learning exercise, I am unclear how I can construct and apply regexp to the string with commas.
Stretch question: How can I quickly identify there are string elements which DO NOT follow one or more of the patterns.
Thanks
What I have so far is:
(a) ^\d{0,5}*$
(b) ^\d{0,5}-\d{0,5}*$
(c) (?:z)
(d) (?:r)
(e) (?:odd|even)
so code extract:
$reg1 = '^\d{0,5}*$'
$reg2 = '^\d{0,5}-\d{0,5}*$'
$reg3 = '(?:z)'
$reg4 = '(?:r)'
$reg5 = '(?:odd|even)'
This is applied to the string split into array elements.
$phase1 = $rangearray | Select-String $reg1 -AllMatches | %{$_.Line} | sort # single numbers only
if($phase1.count -gt 0) { $Allpages[0].Single = $true; $Allpages[1].Single = @($phase1); }
$phase1 = $rangearray | Select-String $reg2 -AllMatches | %{$_.Line} # number ranges
if($phase1.count -gt 0) { $Allpages[0].Ranged = $true; $Allpages[1].Ranged = {$phase1}.Invoke(); }
$phase1 = $rangearray | Select-String $reg3 -AllMatches | %{$_.Line} # max range option z
if($phase1.count -gt 0) { $Allpages[0].Z = $true; $Allpages[1].Z = @($phase1); }
$phase1 = $rangearray | Select-String $reg5 -AllMatches | %{$_.Line} # odds and evens
if($phase1.count -gt 0) { $Allpages[0].OddEven = $true; $Allpages[1].OddEven = @($phase1); }
This function is passed a string. Examples of that string are below:
$range = '1-2,12-14,27-25,300-270,r10-r15,450-470:odd'
$range = '4, 2, 5, 14-12,16-18,20-19,r3-r1,285-290,r7-r4,388-z'