user1701450
user1701450

Reputation: 72

How to create a Regex pattern that returns digits after string - C#

I am trying to create a Pattern that returns me results as shows below given list :

Help # 7256
Help # 83930
ph  # 7222
this is a test example
Help # 029299
New # 92929

output :

Help # 7256 
Help # 83930 
Help # 029299

Anything that starts with Help following by # sign then followed by 3 , 4 , 5 digit value

I tried something like this

Regex pattern = new Regex(@"(Help #) (^|\D)(\d{3, 4,5})($|\D)");

Can someone please help me with creating this patten ? (in C#)

Upvotes: 0

Views: 381

Answers (3)

Adam K Dean
Adam K Dean

Reputation: 7475

For C#, try this:

var list = new string[] { 
    "Help", "Help # 7256", "Help # 83930", 
    "ph # 7222", "this is a test example", 
    "Help # 029299", "New # 92929",
    "Help # 7256 8945", "Help # 83930 8998 787989"
};

// bear in mind that the $ at the end matches only these strings
// if you want it to match something like Help # 1284 12841 0933 SUBJECT HERE"
// then remove the $ from the end of this pattern
const string pattern = @"^(Help)\s#\s(\d{3,6})\s?(\d{3,6})?\s?(\d{3,6})?$";

var regex = new Regex(pattern);
foreach (string s in list)
{
    if (regex.Match(s).Success)
        Console.WriteLine(s);
}
Console.WriteLine("Done.");
Console.ReadKey();

Outputs:

Help # 7256
Help # 83930
Help # 029299
Help # 7256 8945
Help # 83930 8998 787989

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

A simple solution, assuming that you want to get all lines that starts with Help # (regardless of what comes after it), and the format of the input file is consistent:

if (currentLine.StartsWith(@"Help #"))
{
    // Do something with the line
}

String.StartsWith method reference.

If you want regex solution, here is the regex (in literal string):

@"^Help #\s+(\d+)"

This can be used with Regex.Match(String). You can pick up the number from the capturing group 1. This one will only match line that starts with Help # followed by any number of spaces, then at least 1 digit. Note that this regex is only OK to use if you are scanning your file line by line.

If you must limit it to 3-5 digits:

@"^Help #\s+(\d{3,5})"

Upvotes: 2

h2ooooooo
h2ooooooo

Reputation: 39532

/^Help\s*#\s*(\d{3,5})/gm

Demo

I should add that this also matches Help # 029299 like specified in the OP, even though it contains 6 characters.

If you only want to match 3 to 5 characters, this will do it:

/^Help\s*#\s*(\d{3,5})\b/gm

Demo

Note: If you ONLY want to match "Help[SPACE]#[SPACE]number", then simply remove all the \s*'s.

Upvotes: 3

Related Questions