0

I need to extract sections of a string but I won't always know the length/content.

I've tried converting the string to XML or JSON for instance, and can't come up with any other way to achieve what I'm looking for.

Example string:

'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'

What I need to remove always starts with an attribute name and ends with a closing double quote. So can I say I'd like to remove substring starting at Name=" and go until we reach the closing "?

Expected result:

'Other parts of the string blah blah'
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

3 Answers3

1

You'll want to do something like this

$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace ' Name=".*?"'

or like this:

$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace ' Name="[^"]*"'

to avoid unintentionally removing other parts of your string in case it contains multiple attributes or additional double quotes. .*? is a non-greedy match for a sequence of any character except newlines, so it'll match up to the next double quote. [^"]* is a character class matching the longest consecutive sequence of characters that aren't double-quotes, so it'll also match up to the next double quote.

You'll also want to add the miscellaneous construct (?ms) to your expression if you have a multiline string.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

Here is a good reference: https://www.regular-expressions.info/powershell.html

In your case

$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace '\W*Name=".*"\W*', " "

or

$newString = $s -replace 'W*Name=".*"\W*', " "

This will replace your matching string, including the surrounding whitespace, with a single space.

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
0

Look at something like this and understand how it works.

$pattern = '(.*)Name=".*" (.*)'
$str = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'

$ret = $str -match $pattern

$out = $Matches[1]+$Matches[2]

$str
"===>"
$out

See also: https://regex101.com/r/wM2xlc/1

Kory Gill
  • 6,993
  • 1
  • 25
  • 33