Regex how can I merge execution

Viewed 49

I have the following buffer returning from a .textContent

            Latitude

    

    32,6549581304256 

    

        Longitude

    

    -16,9288643331225 

I fixed the whitespaces with dwText = Regex.Replace( dwText, @"\s{2,}", "\n"); resulting in

Latitude
32,6549581304256
Longitude
-16,9288643331225

I then transformed this new output to my needs by dwText = Regex.Replace( dwText, @"(Latitude|Longitude)(.*)\n", "$1: "); resulting in

Latitude: 32,6549581304256
Longitude: -16,9288643331225

My question is can i do these 2 lines in one go?

dwText = Regex.Replace( dwText, @"\s{2,}", "\n");
dwText = Regex.Replace( dwText, @"(Latitude|Longitude)(.*)\n", "$1: ");

I would appreciate some help on how this can be achieved more efficiently, thank you.

3 Answers

Try the following (with i flag),

[\S\s]*?([a-z]+)[\S\s]*?([-\d,]+)[\S\s]*?

Replacement: $1: $2\n

C# Regex Demo


Explanation

  • [\S\s]*? - matches anything lazily.
  • [a-z]+ (first capture group) - matches alphabetical words, case insensitive.
  • [-\d,]+ (second capturing group) - matches digits, - (hyphen) and , (comma)

You can match the whitespace chars around the Latitude and Longitude and capture the values in 2 groups and use those 2 groups in the replacement.

\s*\b(Latitude|Longitude)\s*(-?[0-9]+(?:,[0-9]+)?)\b

Explanation

  • \s* Match 0+ whitespace chars
  • \b(Latitude|Longitude) A word boundary, capture either latitude or Longitude in group 1
  • \s* Match 0+ whitespace chars
  • (-?[0-9]+(?:,[0-9]+)?) Capture group 2, match optional -, 1+ digits with an optional decimal part
  • \b A word boundary

Replace with:

$1: $2\n

.Net regex demo

enter image description here

Why not parse the values out and then extract them to do what is needed with them?

By using match group named captures (?<{NameHere}> ) one can organize and then extract the data.

Example white space shortened, but it works across lines and with the original example:

var data    = " Latitude  32,6549  Longitude  -16,9288 ";
var pattern = @"[^\d]+(?<Lat>[\d,]+)[^\d]+(?<Long>[\d,]+)";

var mtch = Regex.Match(data, pattern);

Console.WriteLine($"Latitude: {mtch.Groups["Lat"].Value} Longitude: {mtch.Groups["Long"].Value}");

// Latitude: 32,6549 Longitude: 16,9288
Related