ironcurtain
ironcurtain

Reputation: 690

Regular expression - secong group of digits

Hi I would like to pull second group of digits which are after (-) from below string:

D:\data\home\Logs_Audit\VO12_LAB_20140617-000301.txt

I used \d{8} to pull 20140617 but now I want to pull 000301

EDIT 1:

Now I would Like to pull VO12_LAB from above string. Could You please help me. I am not good at regular expression and I didn't find good tutorial to understand it.

EDIT 2: I found that something like

\w{2,3}\d{2,3}_\w{2,3}

works to me. Do you think it is accurate enough?

Upvotes: 0

Views: 44

Answers (3)

hwnd
hwnd

Reputation: 70750

You can use a Positive Lookahead for this.

\d+(?=\.)

Explanation: This matches digits (1 or more times) preceded by a dot .

\d+          digits (0-9) (1 or more time)
(?=          look ahead to see if there is:
  \.           '.'
)            end of look-ahead

Live Demo

Final Solution:

String s = @"D:\data\home\Logs\V_LAB_20140617-000301.txt";
Match m  = Regex.Match(s, @"\d+(?=\.)");
if (m.Success) {
   Console.WriteLine(m.Value); //=> "000301"
} 

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

You can use lookahead/lookbehind to find the group based on "anchors", like this:

(?<=[-])\\d+(?=[.]txt)

The groups before and after the \\d+ are non-capturing zero-width "markers", in the sense that they do not consume any characters from the string, only describe character combinations that need to precede and/or follow the text that you would like to match.

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59292

You can use this regex:

(?<=-)(\d+)

The first group will contain the digits.

Live Demo

Upvotes: 0

Related Questions