0

I want to match:

!argument1 [argument2], where argument2 is optional. I have it figured out using a second optional group, but I can't get it to ignore the space between the arguments.

regex="!([a-z]) ?\W(.)"

Matches: "!test case"

"!test "

Not matching: "!test"

I tried to throw in an '?(: )' in the regex to make a non capturing optional group containing the space but to no avail, resulting in the following: regex="!([a-z])?(: )?\W(.)"

The result is 'raise error, v # invalid expression'

some tries usin the python shell:

>>>  regex="!([a-z]*) ?\W(.*)"
>>> data="!hello dear"
>>> re.search(regex, data).groups()
('hello', 'dear')
>>> data="!hello "
>>> re.search(regex, data).groups()
('hello', '')
>>> data="!hello"
>>> re.search(regex, data).groups()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
6
  • It should be !([a-z]+) Commented Jul 28, 2014 at 10:54
  • You've only made the space optional. The second group is mandatory. Commented Jul 28, 2014 at 10:59
  • could you post the actual input and expected output? Commented Jul 28, 2014 at 11:06
  • user3218114: my wildcard is missing due to formatting. user2357112: Well yes, but I dont mind if its empty. Is it better if I add the (optional) whitespace to the secondary group and when I want to make use of that data I simply strip the whitespace? Commented Jul 28, 2014 at 11:16
  • Why u need a space before \W \W (means non word char) so you can simply use !([a-z]+)\W?(.*) optional non word char followed by second group which is captured then Commented Jul 28, 2014 at 11:32

2 Answers 2

1

The regex in the comments should fullfill your requirements !([a-z]+) ?(.*) You require a ! followed by a sequence of characters (your first argument) then there might be a space and another capturing group which could be empty(so missing) or contain any characters after the space

Sign up to request clarification or add additional context in comments.

Comments

0

Overcomplicated.

import re
e = re.compile("(!?\w+)")
s = "!test ing code"
args = e.findall(s)[0][0]
print args

['!test', 'ing', 'code']

then just check if args[0][0] == "!"

I assume this is for a bot of some sort, probably an IRC one, could look at phenny.

Even easier would be to see if your commands starts with ! and strip it before branching to the regex parser. Then you can just capture \w+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.