How to find all matches in a string

Suppose I have the following line:

xx ## A # 11 ## YYY ## bb # 2 ## g

Im trying to get all occurrences ##something#somethingElse##

(On my line, I want to have 2 matches: ##a#11##and ##bb#2##)

I tried to get all matches using

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

but it gets one match, which is a whole string.

How can I get all matches from this line? Thank.

+4
source share
2 answers

.* , . , .* # 1 , .

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

regex

. ## # 1 char # ##, * ( 0+ ) + ( 1+ ).

2: ####..#....#####, : "(?<!#)##[^#]+#[^#]+##(?!#)"

:

  • ## - 2 #
  • [^#]*/[^#]+ - a , 0+ ( 1+ ), #
  • # - #
  • [^#]*/[^#]+ - 0+ ( 1+) , #
  • ## - #.

BONUS: ## ##, , (...) , , Match.Groups[1].Value s:

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

Regex101

Regex.Matches(MyString, "(##[^#]+#[^#]+##)")


(##[^#]+#[^#]+##)

1st Capturing Group (##[^#]+#[^#]+##)
    ## matches the characters ## literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    # matches the character # literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    ## matches the characters ## literally (case sensitive)

Regular expression visualization

Debuggex

+4

Source: https://habr.com/ru/post/1676358/


All Articles