0

I have a string in excel that I need to extract a substring from

This is an example of the string:

<\Text Name="Text5"><TextValue>Hostname:   hostnamehere</TextValue>

I'm new to regex and powershell, but I'm trying to find a way to extract the "hostname here" portion of the string. It's variable length, so indexing won't be reliable.

3
  • try using $VarName.Split(':')[-1].Trim() ... [grin] Commented Jun 17, 2019 at 18:21
  • I had to fix the original question by cancelling out the tags. The Split function isolates the hostname but leaves the trailing tag. I tried splitting it again but I'm getting errors in console (still new to PS, I'm likely using bad parameters) Commented Jun 17, 2019 at 18:35
  • please take a look a the answer i posted. [grin] Commented Jun 17, 2019 at 18:39

2 Answers 2

1

since you changed the sample, the comment code i posted won't work. [grin] this will, tho ...

$InStuff = '<\Text Name="Text5"><TextValue>Hostname:   hostnamehere</TextValue>'

$InStuff.Split(':')[-1].Split('<')[0].Trim()

output = hostnamehere

if you have a set of sample strings, then you likely otta post them so the code can be arranged to handle the needed variants.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide a quick explanation for me on how how trim() works?
when there is no text in the parens, the .Trim() string method removes whitespace at both ends of the string. there are also .TrimEnd() and .TrimStart() for when you want to be more targeted. finally, they all trim characters [not strings] from the target until there are none left to trim. that means it will trim everything in the parens from the target working from the outside of the target string. so this >>> '123asd098'.Trim('810')`` <<< will give you 23asd09`.
0

If that were xml, it would be straightforward

[xml]$xml = '<Text Name="Text5"><TextValue>Hostname:   hostnamehere</TextValue></Text>'
(-split $xml.text.textvalue)[1]

hostnamehere

1 Comment

It's XML, but because there's a custom schema powershell wasn't reading it properly. So now I'm working on parsing the plaintext.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.