tags:

views:

161

answers:

4

I am trying to write a regex string to match a string revived from an IRC channel.

The message will be in the format "!COMMAND parameters"; the only command that is built by the system so far is repeat.

The regex I am using looks like this:

/![repeat] (.*?)/

When other commands are added it will look like:

/![cmd1|cmd2|cmd3] (.*?)/

It does not seem to be matching the right things in the string. Can anyone offer any input on this?

It appears that I need to add some basic regex stuff.

() brackets return data, [] matches but does not return.

Swapping to () does not work either.

The IRC program I am writing has a dynamic number of commands, so far I have only added "repeat" so the command pattern is "[repeat]". If I added "say", it would be "[repeat|say]".

A: 

You're doing one thing wrong. If you replace your [] brackets with () everything should work. Between [] you put some letters to match. [abc] would match a, b, or c, not "abc", while (abc) would match "abc" and (abc|bca) would match "abc" or "bca".

Check out the Perl regular expressions tutorial and reference for more information.

adamse
+3  A: 

Use the parentheses for grouping:

/!(cmd1|cmd2|cmd3) (.*)/

The brackets […] denote a character class describing just one character out of a set of characters.

You should also not use a non-greedy .* as the minimal match of .*? is an empty string.

Gumbo
+1  A: 

You used bad brackets

/!(cmd1|cmd2|cmd3) (.*)/

I don't understand what did you mean with ? in your regex

Gaim
The `?` makes the match non greedy.
adamse
Really thank you for your explanation. I didn't know that.
Gaim
A: 

[repeat] is a character class and will match r or e or p etc..., you should just use

/!repeat (.*?)/

and

/!(cmd1|cmd2|cmd3) (.*?)/

I don't understand exactly what you are hoping to match, but the lazy operator seems wrong for example

/!COMMAND (.*?)/ applied to !COMMAND paramater will match !COMMAND only, (.*?) at the end of a regex is guaranteed to match nothing.

Paul Creasey