Home > Mobile >  Extract number after specific word and first open parenthesis using regex in C#
Extract number after specific word and first open parenthesis using regex in C#

Time:01-09

i want to get a string from a sentence which starts with a word Id:

Letter received for the claim Id: Sanjay Kumar (12345678 / NA123456789) Dear Customer find the report

op: Id: Sanjay Kumar (12345678 / NA123456789)

Exp op: 12345678

Code

  var regex = new Regex(@"[\n\r].*Id:\s*([^\n\r]*)");
  var useridText = regex.Match(extractedDocContent).Value;

CodePudding user response:

You can use

var regex = new Regex(@"(?<=Id:[^()]*\()\d ");

See the regex demo.

Details:

  • (?<=Id:[^()]*\() - a positive lookbehind that matches a location that is immediately preceded with Id: zero or more chars other than ( and ) (
  • \d - one or more digtis.

Consider also a non-lookbehind approach:

var pattern = @"Id:[^()]*\((\d )";
var useridText = Regex.Match(extractedDocContent, pattern)?.Groups[1].Value;
  • Related