简体   繁体   中英

C# Regex extract value between string multiple occurrences

I have a text like this

#-cmd1-# Hakona Matata #-cmd2-#

I want to get all values that is like this #-TEXT-#

Here's the code I use, but it works only when there's one occurrence

var text = "#-adsfree-# hakona matata #-adsbottom-#";

Regex regex = new Regex("#-(.*)-#");
var v = regex.Match(text);
string s = v.Groups[1].ToString();

I'm guessing that you might be designing an expression, maybe similar to:

(?<=#-)\b(\w+)\b(?=-#)

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?<=#-)\b(\w+)\b(?=-#)";
        string input = @"#-adsfree-# hakona matata #-adsbottom-#";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.

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