Codehelp
Codehelp

Reputation: 4747

Get a specific part from a string based on a pattern

I have a string in this format:

ABCD_EFDG20120700.0.xml

This has a pattern which has three parts to it:

  1. First is the set of chars before the '_', the 'ABCD'
  2. Second are the set of chars 'EFDG' after the '_'
  3. Third are the remaining 20120700.0.xml

I can split the original string and get the number(s) from the second element in the split result using this switch:

\d+

Match m = Regex.Match(splitname[1], "\\d+");

That returns only '20120700'. But I need '20120700.0'.

How do I get the required string?

Upvotes: 1

Views: 739

Answers (2)

shA.t
shA.t

Reputation: 16958

I can suggest you to use one regex operation for all you want like this:

var rgx = new Regex(@"^([^_]+)_([^\d.]+)([\d.]+\d+)\.(.*)$");
var matches = rgx.Matches(input);
if (matches.Count > 0)
{
    Console.WriteLine("{0}", matches[0].Groups[0]);  // All input string
    Console.WriteLine("{0}", matches[0].Groups[1]);  // ABCD
    Console.WriteLine("{0}", matches[0].Groups[2]);  // EFGH
    Console.WriteLine("{0}", matches[0].Groups[3]);  // 20120700.0
    Console.WriteLine("{0}", matches[0].Groups[4]);  // xml
}

Upvotes: 0

dotnetom
dotnetom

Reputation: 24901

You can extend your regex to look for any number of digits, then period and then any number of digits once again:

Match m = Regex.Match(splitname[1], "\\d+\\.\\d+");

Although with such regular expression you don't even need to split the string:

string s = "ABCD_EFDG20120700.0.xml";
Match m = Regex.Match(s, "\\d+\\.\\d+");
string result = m.Value;     // result is 20120700.0

Upvotes: 1

Related Questions