简体   繁体   中英

How can I grab a value from this string using regEx in c# explain the regex?

I have a string and I need to parse it for a value...

var msg = "Sometext can't do this. Blah blah blah Version id: 'xxx'";

How can I use regex and get the text between the last two single quotes? xxx Notice the first single quote in {can't} The value I'm seeking will always be between the last set on single quotes. A brief explanation of the regex would be awesome as well.

Thanks so much for any help, tips, examples.

This is the final Regex

    (?<=')[^']*(?='$)

The general pattern I use is

    (?<=prefix)find(?=suffix)

It finds a pattern that lies between a prefix and a suffix. What we want to find is

    [^']*

This means anything but the single quote ( ' ) repeated zero or more times.

Finally we look for '$ at the end, not just ' . This means that the single quote must be at the end of the line.

you can try this

'\w*'

Its simple to understand, \\w - looks for alphanumeric characters , * makes it look for any number of repetitions, and its enclosed in single quotes means looking for anynumber of alphanumeric characters enclosed in single quotes.

In that particular string ...

@"'\w+'"

...will match "'xxx'" , but if you know the string will always end with "Version id: 'xxx'" and you want to account for other text that may be surrounded by single quotes, you can use this...

@"Version id: '(?<versionId>\w+)'$"

...and then retrieve the version ID with this...

Match match = Regex.Match(msg, @"Version id: '(?<versionId>\w+)'$");

if (match.Success)
{
    string versionId = match.Groups["versionId"].Value;

    // Perform further processing on versionId...
}

The regular expression breaks down like this:

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