[英]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.
xxx请注意{cantt}中的第一个单引号我要查找的值将始终在单引号的最后一个引号之间。 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. \\ w-简单易懂,查找字母数字字符,*使它查找任意数量的重复,并且用单引号引起来意味着查找用单引号引起来的任意数量的字母数字字符。
In that particular string
... 在那个特定的
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... ...将匹配
"'xxx'"
,但是如果您知道string
将始终以"Version id: 'xxx'"
结尾,并且您想考虑可能用单引号引起来的其他文本,则可以使用此字符串。 ..
@"Version id: '(?<versionId>\w+)'$"
...and then retrieve the version ID with this... ...然后使用此名称检索版本ID ...
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: '"
Version id: '
=文字文本"Version id: '"
(?<versionId>\\w+)
= A group that you can access by name ( "versionId"
) (?<versionId>\\w+)
=可以通过名称访问的组( "versionId"
) \\w+
= One or more occurrences of a word character (letters, digits, and punctuation). \\w+
= 一个或多个 单词字符 (字母,数字和标点符号)出现。 If you're looking to match only decimal digits , you can use \\d+
instead. \\d+
。 '
= literal text "'"
'
=文字"'"
$
= anchors the match to the end of the line or string
$
=将匹配项锚定到行或string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.