简体   繁体   中英

Matching string separated by - using regex

Regex is not my favorite thing, but it certainly has it's uses. Right now I'm trying to match a string consisting of this.

[video-{service}-{id}] 

An example of such a string:

[video-123abC-zxv9.89]

In the example above I would like to get the "service" 123abC and the "id" zxv9.89.

So far this is what I've got. Probably overcompliacated..

var regexPattern = @"\[video-(?<id1>[^]]+)(-(?<id2>[^]]+))?\]";
var ids = Regex.Matches(text, regexPattern, RegexOptions.IgnoreCase)
    .Cast<Match>()
    .Select(m => new VideoReplaceItem()
    {
        Tag = m.Value,
        Id = string.IsNullOrWhiteSpace(m.Groups["id1"].Value) == false ? m.Groups["id1"].Value : "",
        Service = string.IsNullOrWhiteSpace(m.Groups["id2"].Value) == false ? m.Groups["id2"].Value : "",
    }).ToList();

This does not work and puts all the charachters after '[video-' into into Id variable.

Any suggestions?

The third part seems to be optional. The [^]]+ is actually matching the - symbol, and to fix the expression, you either need to make the first [^]]+ lazy ( [^]]+? ) or add a hyphen to the negated character class.

Use

\[video-(?<id1>[^]-]+)(-(?<id2>[^]-]+))?]

See the regex demo

Or with the lazy character class:

\[video-(?<id1>[^]]+?)(-(?<id2>[^]]+))?]
                    ^

See another demo .

Since you are using named groups, you may compile the regex object with RegexOptions.ExplicitCapture option to make the regex engine treat all numbered capturing groups as non-capturing ones (so as not to add ?: after the ( that defines the optional (-(?<id2>[^]-]+))? group).

Try this:

\[video-(?<service>[^]]+?)(-(?<id>[^]]+))?\]

The "?" in the service group makes the expression before it "lazy" (meaning it matches the fewest possible characters to satisfy the overall expression).

I would recommend Regexstorm.net for .NET regex testing: http://regexstorm.net/tester

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