简体   繁体   中英

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

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM