Home > OS >  How can I extract double values of a string without space, just characters for identification
How can I extract double values of a string without space, just characters for identification

Time:11-03

I am working on a plugin for CAM software and one of the methods is to extract the data, double values, from the CNC machine file .txt that the software generates. An example of it would be: N0310X3.6849Y0.9048Z-0.1656

The values I'm looking for are the ones followed by: X, Y, and Z. Those are coordinates. I need to find a way to extract those values, knowing that the lines may not have all coordinates or even any of them. I thought of using a loop to iterate each character and a lot of if conditions to copy to another string. I see that this is a terrible way, but couldn't manage to think of anything else.

Normally the lines would have a space between the commands and for that, I already found an easy way to handle the values.

CodePudding user response:

You can try using regular expressions in order to match name / value pairs:

using System.Linq;
using System.Text.RegularExpressions;

  ...  

string text = "N0310X3.6849Y0.9048Z-0.1656";

var result = Regex
  .Matches(text, @"(?<name>\p{L} )(?<value>-?[0-9] (\.[0-9] )?)")
  .Cast<Match>()
  .Select(match => (
     name : match.Groups["name"].Value,
     value : double.TryParse(match.Groups["value"].Value, out var v) ? v : double.NaN))
  .Where(pair => !double.IsNaN(pair.value))
  .ToArray();

Pattern (?<name>\p{L} )(?<value>-?[0-9] (\.[0-9] )?) explained:

(?<name>\p{L} ) named group where
   name        - group has name "name"
   \p{L}       - one or more unicode letters 
(?<value>-?[0-9] (\.[0-9] )?) named group where
   value       - group has name "value"
   -?          - optional -
   [0-9]       - one or more digits in 0..9 range
   (\.[0-9] )? - optional group (fractional part):
     \.        - decimal separator
     [0-9]     - one or more digits in 0..9 range 

Let's have a look:

Console.Write(string.Join(Environment.NewLine, result));

Output:

(N, 310)
(X, 3.6849)
(Y, 0.9048)
(Z, -0.1656)
  • Related