0

I'm practicing PowerShell on Codewars. I'm currently struggling with this rather easy exercise.

My problem is that my match is not matching correctly or I haven't understood what kind of string the Input is. I'm trying find the data set to a given number. The input is a string, representing a phonebook. The information in each set is in a random order.

So I already tried to first split the input after every new line (-split "\n"). Didn't work, so I tried it with match. (e.g. -match ".*48-421-674-8974.*\n"). Now what I would expect in Matches, is all information to that number until the next '\n'. But instead I'm getting the data set I wanted PLUS the next line. I've already tried \\n, \\\\n, single/double quotes. But I can't find any solution by myself.

So currently my input is this:

"<Sophia Loren> +1-421-674-8974 Bern TP-46017\n <Peter O'Brien> High  
Street +1-908-512-2222; CC-47209\n"*
"<Anastasia> +48-421-674-8974 Via Quirinal Roma\n <P Salinger> 
Main  Street, +1-098-512-2222, Denver\n"*
"<C Powel> *+19-421-674-8974 Chateau des Fosses Strasbourg F-68000\n 
<Bernard >Deltheil +1-498-512-2222; Mount Av.  Eldorado\n"

And my regex ".*48-421-674-8974.*\\n"

(My Regex online)

I'd expect this result:

<Anastasia> +48-421-674-8974 Via Quirinal Roma\n

but I'm getting:

"<Anastasia> +48-421-674-8974 Via Quirinal Roma\n <P Salinger> Main Street, +1-098-512-2222, Denver\n"

I've also tried matching or spliting again after this result, but that did'nt work either.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Schulaa
  • 3
  • 2

2 Answers2

1

.* is a greedy match. What you want is a non-greedy match (.*?) starting with an opening angular bracket, including the phone number, and ending with a literal backslash and the character "n".

$inputText = @'
"<Sophia Loren> +1-421-674-8974 Bern TP-46017\n <Peter O'Brien> High Street +1-908-512-2222; CC-47209\n"*
"<Anastasia> +48-421-674-8974 Via Quirinal Roma\n <P Salinger> Main  Street, +1-098-512-2222, Denver\n"*
"<C Powel> *+19-421-674-8974 Chateau des Fosses Strasbourg F-68000\n <Bernard >Deltheil +1-498-512-2222; Mount Av. Eldorado\n"
'@

$pattern = '<.*?48-421-674-8974.*?\\n'

$inputText |
    Select-String -Pattern $pattern -AllMatches |
    Select-Object -Expand Matches |
    Select-Object -Expand Value
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

I have imported your input text (keeping the \n characters intact) and wrote this line that does the regex matching:

([regex]".*48-421-674-8974[a-zA-Z ]+\\n").Matches($text)

Now it might happen that if you load the actual phone address data from a file, the newline character might need to be specified like Wiktor Stribizew said as a "`n"

mklement0
  • 382,024
  • 64
  • 607
  • 775
Dandré
  • 2,053
  • 3
  • 18
  • 38