Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find in string all matches

Tags:

c#

regex

Assume that I have the following string:

xx##a#11##yyy##bb#2##z

Im trying to retrieve all occurrence of ##something#somethingElse##

(In my string I want to have 2 matches: ##a#11## and ##bb#2##)

I tried to get all matches using

Regex.Matches(MyString, ".*(##.*#.*##).*")

but it retrieves one match which is the whole row.

How can I get all matches from this string? Thanks.

like image 788
Nir Avatar asked Feb 05 '23 12:02

Nir


1 Answers

Since you have .* at the start and end of your pattern, you only get the whole line match. Besides, .* in-between #s in your pattern is too greedy, and would grab all the expected matches into 1 match when encountered on a single line.

You may use

var results = Regex.Matches(MyString, "##[^#]*#[^#]*##")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToList();

See the regex demo

NOTE: If there must be at least 1 char in between ## and #, and # and ##, replace * quantifier (matching 0+ occurrences) with + quantifier (matching 1+ occurrences).

NOTE2: To avoid matches inside ####..#....#####, you may add lookarounds: "(?<!#)##[^#]+#[^#]+##(?!#)"

Pattern details:

  • ## - 2 # symbols
  • [^#]* / [^#]+ - a negated character class matching 0+ chars (or 1+ chars) other than #
  • # - a single #
  • [^#]* / [^#]+ - 0+ (or 1+) chars other than #
  • ## - double # symbol.

BONUS: To get the contents inside ## and ##, use a capturing group, a pair of unescaped (...) around the part of the pattern you need to extract, and grab Match.Groups[1].Values:

var results = Regex.Matches(MyString, @"##([^#]*#[^#]*)##")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value)
    .ToList();
like image 100
Wiktor Stribiżew Avatar answered Feb 08 '23 14:02

Wiktor Stribiżew