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:
(?<=,"|\?<=,).*(?=",.*?|\?=,.*?)
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?"
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 ,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With