Click here to Skip to main content
14,971,029 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey all,
I'm trying to use named group to parse a string.

An example is:
exitcode: 0; session id is RDP-Tcp#2

and my try is:
("(exitCode)+(\s)*:(\s)*(?<exitCode>[^;]+)(\s)*;(\s)*(session id is)(\s)*(?<sessionID>[^;]*)(\s)*");

Where do I syntacticaly wrong?
Thanks


[Edit: Add RegEx To Title]
Posted
Updated 9-Jul-10 9:37am
v2

See this page on the use of Named Groups;

http://regexadvice.com/blogs/dneimke/archive/2005/01/13/256.aspx[^]
   
What makes you think there is something syntactically incorrect? Did you get an error message? What is the C# code you're using to run this regular expression (that will let us know, for example, if you are ignoring whitespace or if you are ignoring case)? Also, I'm not sure what variety of input strings you are trying to match, but I imagine your regex is incorrect at least based on that first match condition. For example, this will probably show up as a match:
exitcodeexitcodeexitcode: 0; session id is RDP-Tcp#2

Also, I'm not sure why you check for a trailing semicolon at the end of your regex, as there is no trailing semicolon (perhaps there is sometimes?).
   
"I get a curved line under (\s)*
and a message:
Error 1 Unrecognized escape sequence"

The reason is simple:
"(exitCode)+(\s)*:(\s)*(?<exitCode>[^;]+)(\s)*;(\s)*(session id is)(\s)*(?<sessionID>[^;]*)(\s)*"
The '\' character is being interpretted as a C# string escape, and it is trying to tell you that it doesn't know the escape sequence '\s'. To fix, either replace the '\' characters with '\\', or put an '@' character before the opening double quote:
@"(exitCode)+(\s)*:(\s)*(?<exitCode>[^;]+)(\s)*;(\s)*(session id is)(\s)*(?<sessionID>[^;]*)(\s)*"

For your actual regex, try this:
public static Regex regex = new Regex(
      "(?:exitcode\\s*\\:\\s*)(?<ExitCode>\\d*)(?:\\s*;\\s*session\\sid\\s"+
      "is\\s)(?<SessionCode>.*)",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );


It is well worth getting a copy of Expresso
Expresso[^] It's free and it really helps work out regexes!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900