简体   繁体   中英

Get value using regex from string KP{{seq:2}}

See below example for more details,

Ex :

  1. If I have string Demo19 of pattern Demo{{seq:2}} (Where 2 is length of digits) then I should get output as 19
  2. Demo191 of pattern Demo{{seq:3}} => Output: 191
  3. Demo19Test1 of pattern** Demo19Test{{seq:1}} ** => Output: 1 (Based on sequence)
  4. Demo19KPTest1Demo of pattern** Demo19KPTest{{seq:1}}Demo ** => Output: 1 (Based on sequence)

Demo,test,KP are just string

Its as easy as the following pattern

(?<=KP)\d+\b

The way to read this

  • (?<=subpattern) : Zero-width positive lookbehind assertion. Continues matching only if subpattern matches on the left .

  • \\d : Matches any decimal digit.

  • + : Matches previous element one or more times.

  • \\b : reduces backtracking.

Example

var regex = new Regex(@"(?<=KP)\d+\b", RegexOptions.IgnoreCase);
var match = regex.Match(input);

if (match.Success)
{
   Console.WriteLine(match.Value);
}

Demo

https://regex101.com/r/879sPF/1

If I understand what you want, I think this code can help you:

// This means you want to find `KP` followed by a fixed sequence of numbers
var pattern = @"KP(\d{" + seq + "})"; 
var result = Regex
            .Matches(txt, pattern)
            .OfType<Match>()
            .Select(c => int.Parse(c.Groups[1].Value))
            .ToList();

[ C# Demo ]
or

var result = Regex
            .Matches(txt, @"KP(\d+)")
            .OfType<Match>()
            .ToList()[seq - 1]
            .Groups[1].Value;

[ C# Demo ]

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