tags:

views:

47

answers:

2

Hi,

I've got two possible string inputs that my application will receive, and if it matches the following two strings, I need it regex.ismatch() to return true:

"User * has logged out"
"User * has joined"

I'm not that good at regex and just can't figure out how to go about matching the above.

Any help would be great!!!

+3  A: 

Assuming that you mean to match * literally as an asterisk, then you need to escape it with a preceding \ as follows.

@"^User \* has (logged out|joined)$"

If by * you mean "any username", then substitute it with either the regex you use to validate your usernames, or for lack of anything better, you can always use just .*.

The (logged out|joined) construct is called an "alternation". The surrounding parentheses, in addition to enforcing precedence on the alternation in this case, also captures into group 1 either the string "logged out" or "joined", depending on which alternate matches.

If you don't need to distinguish between the two events, then you don't really need this string captured, and you can use a non-capturing group (?:logged out|joined), for slight performance gain.

The ^ and $ are what are called anchors, which respectively match the beginning and end of the string. Proper placement of these anchors in the pattern ensures that it matches the entirety of the input string, not just a substring.

regular-expressions.info Links

polygenelubricants
+1  A: 

Assuming * is going to be a username:

"User .+ has (joined|logged out)"

or perhaps something like this (which might need more character options in the username):

"User [A-Za-z0-1_]+ has (joined|logged out)"
Mike Hanson