Reputation: 51
I am trying to get "SubString One" AND "SubString two" the script I am using allows me to have the substring between substring , but :
1) only the first one substring and not all of them 2) Does not support multilines, which means I won't have "SubString One" in the example above
Help Please !
$a = " randomText <style>SubString One
</style>
another randomText <style>SubString two </style>"
$pattern = "<style>(.*?)</style>"
$b = [regex]::Match($a,$pattern).Groups[1].Value
write-host $b
Upvotes: 1
Views: 56
Reputation: 440297
Since your first <style>
element spans two lines, you must turn on the SingleLine regex option in order to make .
also match newlines (line breaks).
To find multiple matches in the input string, use the ::Matches()
rather than the ::Match()
method.
$a = " randomText <style>SubString One
</style>
another randomText <style>SubString two </style>"
# Inline option (?s) (SingleLine) makes '.' match newlines.
$pattern = "(?s)<style>(.*?)</style>"
# Use ::Matches() and .ForEach() to extract the capture-group match
# from each match.
# .Trim() removes surrounding whitespace, notably the newline at the
# end of 'SubString One'
[regex]::Matches($a, $pattern).ForEach({ $_.Groups[1].Value.Trim() })
The above yields:
SubString One
SubString two
Upvotes: 2