Need to split string where alpha+numeric coincide

Tagged: 

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Stephen R Fairbrother Stephen R Fairbrother 3 weeks, 1 day ago.

  • Author
    Posts
  • #69820

    In my string, I have values that are combined like this: Name123456

    I want to separate those instances into separate values in the string.

    I'm guessing wildcards for alpha + numeric are involved but haven't found the right combination.

  • #69823
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Unfortunately, you can't split on wild cards (and indeed, you'd need a regular expression rather than a simple wildcard). A basic -split or String.Split() needs an unambiguous character. So your job is going to be a lot harder than you thought :).

    I'm fairly comfortable with regular expressions, so I'd probably run two matches against the input string. The first match would give made the non-digit characters (\D) and the second the digit characters (\d). If you use a capturing expression with -match, then $matches will be populated with the matching substring.

  • #69828
    Profile photo of Roy Atkins
    Roy Atkins
    Participant

    If you're sure that there are just two substrings, one with characters, the other with digits, you could use a pair of regex capture groups as follows.

    'Name123456' -match '(\D+)(\d+)' ; $Matches
    

    If there are more combinations in the string, you'll need something a little more sophisticated, uses alternation:

    $String = ([regex]::Matches('Name12345Another4567', '(\d+)|(\D+)')).Value
    
    $String
    
  • #69843

    Thanks, Guys.

    I took the coward's way out and did some editing on parentheses and further split some fields then loaded everything in my array. Now I just have to figure out how to pump things out in the order I want to create 2 reports, the second one featuring some sorting. I will try to get back to these methods when I have time. Parsing is fun, once you wrestle the problem to the ground. While it was painful, it was also educational. I hope to further master the ins and outs as I continue my journey with PowerShell. Phone screen for a position tomorrow. I was embarrassed by what I had achieved so far but feeling much better now.

    -Steve

You must be logged in to reply to this topic.