Home > Mobile >  c# regex matches example to extract result
c# regex matches example to extract result

Time:02-01

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?

CodePudding user response:

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.

You can explore the regex above with your match here: 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

CodePudding user response:

you can use this regX :

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

show result

  •  Tags:  
  • c#
  • Related