RegEx pattern problem

Markus Freitag 3,786 Reputation points
2023-10-06T17:52:40.47+00:00

Hello,

I need to split this string into a list. But no pattern works.

The easiest thing would be to get the value of all key words back as a string. What is here the right way?

string pattern = @"\{s_name=(\w+),s_value=([\d.]+),s_unit=([\d.]+[a-zA-Z/]+)\}";
       pattern = @"\{s_name=(\w+),s_value=(^[a-zA-Z.& ]*$),s_unit=([\d.]+[a-zA-Z/]+)\}";

       pattern = @"\{s_name=(\w+),s_value=(\w+[ ]),s_unit=([\d.]+[a-zA-Z/]+)\}";

       pattern = @"\{s_name=(\w+),s_value=(a-zA-Z] ),s_unit=([\d.]+[a-zA-Z/]+)\}";

       pattern = @"\{s_name=(\w+)}";			
				
				
{s_name=length,s_value=240.000,s_unit=1.0mm};{s_name=width,s_value=152.000,s_unit=1.0mm};{s_name=thickness,s_value=1.600,s_unit=1.0mm};{s_name=speed,s_value=45,s_unit=1.0mm/s};
{s_name=position_X, s_value = 240.000, s_unit = 1.0mm };{s_name=position_Y, s_value=240.000, s_unit=}


// OR

{s_name=length,**s_value=240.000 supplier A**,s_unit=1.0mm};{s_name=width,s_value=152.000,s_unit=1.0mm};{s_name=thickness,**s_value=1.600 supplier B **,s_unit=1.0mm};{s_name=speed,s_value=45,s_unit=1.0mm/s};
{s_name=position_X, s_value = 240.000, s_unit = 1.0mm };{s_name=position_Y, s_value=240.000, s_unit=}

s_name    - exist, must be
s_value   - empty or numbers or letters or numbers and letters
s_unit    - empty or numbers or letters

For understanding if I just want numbers? For understanding if I just want numbers or empty? s_value=152.000 or s_value=

Thanks for your help!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,390 questions
{count} votes

Accepted answer
  1. Viorel 113.1K Reputation points
    2023-10-07T08:30:45.9766667+00:00

    Check an example:

    string input = "{s_name=length,s_value=240.000 supplier A,s_unit=1.0mm};{s_name=width,s_value=152.000,s_unit=1.0mm};{s_name=thickness,s_value=1.600 supplier B,s_unit=1.0mm};{s_name=speed,s_value=45,s_unit=1.0mm/s};\r\n{s_name=position_X, s_value = 240.000, s_unit = 1.0mm };{s_name=position_Y, s_value=240.000, s_unit=}\r\n";
    
    string name = "length";
    
    Match m = Regex.Match( input, @"\{\s*s_name\s*=\s*" + Regex.Escape( name ) + @"\s*,\s*s_value\s*=\s*(?<value>.*?)\s*,\s*s_unit\s*=\s*(?<unit>.*?)\s*\}" );
    if( m.Success )
    {
        string value = m.Groups["value"].Value;
        string unit = m.Groups["unit"].Value;
    
        Console.WriteLine( $"s_name = {name}" );
        Console.WriteLine( $"s_value = {value}" );
        Console.WriteLine( $"s_unit = {unit}" );
    
        Match m2 = Regex.Match( value, @"^(\+|-)?\d+(\.\d+)?" );
        if( m2.Success )
        {
            decimal d = decimal.Parse( m2.Value, CultureInfo.InvariantCulture );
            Console.WriteLine( $"numeric value = {d}" );
        }
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful