简体   繁体   English

c# 正则表达式匹配示例提取结果

[英]c# regex matches example to extract result

I am trying to extract a character/digit from a string that is between single quotes and seems like i am failing to write the correct pattern.我正在尝试从单引号之间的字符串中提取字符/数字,似乎我没有写出正确的模式。

Test string - only value that changes is the single character/digit in single quotes测试字符串 - 唯一改变的值是单引号中的单个字符/数字

[+] Random session part: 'm'

I am using the following pattern but it returns empty我正在使用以下模式,但它返回空

        var line = "[+] Random session part: 'm'";
        Regex pattern = new Regex(@"(?<=\')(.*?)(?=\')");
        Match match = pattern.Match(line);
        Debug.Log($"{match.Groups["postfix"].Value}");
        int postFix = int.Parse(match.Groups["postfix"].Value);

what am i missing?我错过了什么?

You have an overly complicated regex, and looking for a group named 'postfix' in you match, while your regex does not have such a named group.您有一个过于复杂的正则表达式,并在匹配中寻找名为“后缀”的组,而您的正则表达式没有这样的命名组。

A simpler regex would be:一个更简单的正则表达式是:

'(.)'

This looks for a single character between two single quotes, and has that character wrapped in a capture group.这会在两个单引号之间查找单个字符,并将该字符包裹在捕获组中。 Put a breakpoint after your match row, and you can explore the matched object.在匹配行后放置一个断点,您可以浏览匹配的 object。

You can explore the regex above with your match here: https://regexr.com/77b0m你可以在这里用你的比赛探索上面的正则表达式: https://regexr.com/77b0m

BTW: Your code tries to parse the string "m" into an int, this will throw and error, your should probably handle that case with int.TryParse顺便说一句:您的代码试图将字符串“m”解析为一个 int,这将引发错误,您应该使用 int.TryParse 处理这种情况

you can use this regX:你可以使用这个 regX:

(?<=\')(.*?)(?=\')

show result显示结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM