C# Regular Expression Matches

Viewed 51

I am writing a function to get the matches from an input string in which I need to extract the matches.

Input samples:

1) QUO-{RANDSTRING:5}-{DATETIMEUTC:yyyy}
2) {RANDSTRING:2}-{RANDNUMBER:4}
3) PREFIX-{RANDSTRING:2}-ANY-TEXT-{RANDNUMBER:4}-SUFIX

The input can be anything like the example above. The text outside the {} can be anything. The text within {} is the relevant part.

So, the regular expression should extract the matches as follow:

Input: QUO-{RANDSTRING:5}-{DATETIMEUTC:yyyy}
Matches: RANDSTRING and DATETIMEUTC

Input: {RANDSTRING:2}-{RANDNUMBER:4}
Matches: RANDSTRING and RANDNUMBER

Input: PREFIX-{RANDSTRING:2}-ANY-TEXT-{RANDNUMBER:4}-SUFIX
Matches: RANDSTRING and RANDNUMBER
1 Answers

I'm assuming you want every sequence of upper-case letters between { and :.

Regex.Matches(input, @"(?<={)[A-Z]+(?=:)")

Explanation:

  • (?<={) looks for a { before the match
  • [A-Z]+ matches at least one upper-case letter
  • (?=:) looks for a : after the match
Related