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:
Version id: '
= literal text "Version id: '"
(?<versionId>\\w+)
= A group that you can access by name ( "versionId"
) \\w+
= One or more occurrences of a word character (letters, digits, and punctuation). If you're looking to match only decimal digits , you can use \\d+
instead. '
= literal text "'"
$
= anchors the match to the end of the line or string
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.