Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match all characters between two commas or between ," and ", with regex powershell

Using powershell regex I would like it to find the first match between two commas or between ," and ",

Example:

"0x00000000","What do you want to eat? fish, meat or\n eggs?",""
"0x00030002","What do you want to eat?",""
0x00030002,What do you want to eat?,

I want it to become:

What do you want to eat? fish, meat or eggs?
What do you want to eat?
What do you want to eat?

I tried this code but it doesn't behave correctly:

(?<=,"|\?<=,).*(?=",.*?|\?=,.*?)

like image 582
Kenryoku Avatar asked Dec 30 '25 21:12

Kenryoku


2 Answers

Rather than using a regular expression for this (which has some pitfalls), I would use the native ConvertFrom-Csv cmdlet for this:

$List = @'
"0x00000000","What do you want to eat? fish, meat or eggs?",""
'"0x00030002","What do you want to eat?",""
0x00000000,What do you want to eat? fish, meat or eggs?,
0x00030002,What do you want to eat?,
"0x00000000","What do you want to eat? ""fish"", ""meat"" or ""eggs?"""
'@ -Split '\r?\n'

$List | ConvertFrom-Csv -Header Hex, String, Rest | Select-Object -Expand String

What do you want to eat? fish, meat or eggs?
What do you want to eat?
What do you want to eat? fish
What do you want to eat?
What do you want to eat? "fish", "meat" or "eggs?"
like image 149
iRon Avatar answered Jan 02 '26 12:01

iRon


You could match:

(?<=,")[^"]*(?=",)|(?<=,)(?!")[^,]*(?<!")(?=,)

Among other things, this matches the following:

"0x00030002","What do you, want to eat?",""
              ^^^^^^^^^^^^^^^^^^^^^^^^^
0x00030002,What do "you want" to eat?,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^

and does not match:

"0x00030002","What do you want to eat?,"
0x00030002 ,What do you want to eat?",

Demo

The expression can be broken down as follows.

(?<=,")  # positive lookbehind asserts current location is preceded by ,"
[^"]*    # match zero or more characters other than "
(?=",)   # positive lookahead asserts current location is followed by ",
|        # or
(?<=,)   # positive lookbehind asserts current location is preceded by ,
(?!")    # negative lookahead asserts current location is not followed by "
[^,]*    # match zero or more characters other than ,
(?<!")   # negative lookbehind asserts current location is not preceded by "
(?=,)    # positive lookahead asserts current location is followed by ,
        
like image 30
Cary Swoveland Avatar answered Jan 02 '26 13:01

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!