Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract specific values using Regex Expression

Tags:

c#

regex

I'm trying to create an expression that extracts strings greater than 125 from a given string input.

var input = "YH300s, H900H, 234, 90.5, +12D, 48E, R180S, 190A, 350A, J380S";

Please view the link for further reference to my script/data example.

DonotFiddle_Regex example

Here is my current expression attempt (*):

Regex.Matches(input,@"(?!.*\..*)[^\s\,]*([2-5][\d]{2,})[^\s\,]*"))

From the above expression, the only output is 350A, J380S.

However I would like to extract the following output from the input string (see link above for further reference):

YH300s, H900H, R180S, 190A, 350A, J380S

Any further guide as to where I may be going wrong would be very much appreciated. Apology in advance if my context is not clear, as I am still novice in writing regex expressions.

like image 270
user3070072 Avatar asked May 28 '15 13:05

user3070072


1 Answers

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        // an example of input
        var input = "YH300s, H900H, 234, 90.5, +12D, 48E, R180S, 190A, 350A, J380S";

        var parts = input.Split(new[]{", "}, StringSplitOptions.RemoveEmptyEntries);
        // regex for numbers (including negative and floating-point)
        var regex = new Regex(@"[-]?[\d]?[\.]?[\d]+");

        foreach(var part in parts)
        {
            // there can be many matches, e.g. "A100B1111" => "100" and "1111"            
            foreach(Match m in regex.Matches(part))
            {
                if (double.Parse(m.Value) > 125)
                {
                    Console.WriteLine(part);
                    break;
                }
            }                   
        }           
    }
}

output

YH300s
H900H
234
R180S
190A
350A
J380S
like image 168
ASh Avatar answered Oct 01 '22 20:10

ASh