regex101: build, test, and debug regex[
^] is a good place to build and test your expressions. It supports many languages including C#.
The reason that you are only getting one result is because of this:
Match m = r.Match(str);
Match
is singular,
Matches
is plural.
Now, to the problem, this will return multiple results, also stripping the marking characters:
string str = "#one# two *three*";
Regex r = new Regex(@"(?<=([#*]))(?:.)*?(?=\1)");
MatchCollection matches = r.Matches(str);
foreach (var match in matches)
Console.WriteLine(match.ToString());
UPDATE:
For your next test, as per the comments below, you can use the following:
string str = "#one# two *three* *four* #five#";
Regex r = new Regex(@"(?<=([#*]))(?:[a-zA-Z])*?(?=([#*]))");
MatchCollection matches = r.Matches(str);
foreach (var match in matches)
Console.WriteLine(match.ToString());
Outputs:
one
three
four
five
As per
regex101: build, test, and debug regex[
^], the breakdown is as follows:
* Positive Lookbehind (?<=([#*]))
- Match a single character present in the list below [#*]
- #* matches a single character in the list #* (case sensitive)
* Non-capturing group (?:[a-zA-Z])*?
- *? matches the previous token between zero and unlimited times,
as few times as possible, expanding as needed (lazy)
- Match a single character present in the list below [a-zA-Z]
* Positive Lookahead (?=([#*]))
- Match a single character present in the list below [#*]
- #* matches a single character in the list #* (case sensitive)