How to convert this PHP RegEx conformance pattern to .Net

This is a fairly complex regular expression that returns an array of key / value pairs from a proprietary data string. Here is sample data in case the expression cannot be used in .Net and another method needs to be used.

0,"101"1,"12345"11,"ABC Company"12,"John Doe"13,"123 Main St"14,""15,"Malvern"16,"PA"17,"19355"19,"UPS"21,"10"22,"GND"23,""24,"082310"25,""26,"0.00"29,"1Z1235550300000645"30," PA 193 9-05"34,"6.55"37,"6.55"38,"8.05"65,"1Z1235550300000645"77,"10"96,""97,""98 

If you look carefully, you will see its key , " value ", key , " value ". The only guarantee when formatting is that each pair of key values ​​is separated by a comma, and each value will always be enclosed in double quotes. The main problem (the reason you cannot split it) is the poor choice of the previous encoder to separate keys and values ​​with the same character as the records. Anyway, out of my hands. Here is an example of how PHP works.

  function parseResponse($response) { // split response into $key, $value pieces preg_match_all("/(.*?),\"(.*?)\"/", $response, $m); // loop through pieces and format foreach($m[1] as $index => $key) { $value = $m[2][$index] echo $key . ":" . $value; // this will output KEY:VALUE for each entry in the string } } 

You can see the expression /(.*?),\"(.*?)\"/

Here is what I have in VB.Net

 Imports System.Text.RegularExpressions Public Class Parser Private Sub parseResponse(ByVal response As String) Dim regExMatch As Match = Regex.Match(response, "/(.*?),\""(.*?)\""/") End Sub End Class 
+4
source share
1 answer

You need to remove the PHP delimiters:

 Dim RegexObj As New Regex("(.*?),""(.*?)""") 

Also, it’s better to clarify what can be matched (makes the regex much more efficient):

 Dim RegexObj As New Regex("([^,]*),""([^""]*)""") 

Now the first group matches only characters that are not commas, and the second only matches characters that are not quotes. By the way, both regular expressions would fail if you had hidden quotes in your data.

To get all matches in a string, use

 AllMatchResults = RegexObj.Matches(response) 
+3
source

Source: https://habr.com/ru/post/1395369/


All Articles