2

I'm trying to get some regex to parse some values stored in a set of lua files, each line looks something like one of these two lines

  1. ITEM.ID = 'item_clock';\r\n
  2. ITEM.Cost = 150;\r\n.

when I run my regex pattern on the first line I get an expected result

>>> re.search("ITEM.(?P<key>[a-zA-Z]\w) = (?P<value>.*);", line).groupdict()
{'key': 'ID', 'value': "'item_clock'"}

however when I run it on the second line, I don't get a Match object.

2 Answers 2

7

The regex looks for ITEM. followed by a letter then followed by exactly one word character (the \w in the regex).

You probably meant something like ITEM.(?P<key>[a-zA-Z]\w*)... (note the added asterisk). This will look for ITEM. followed by a letter then followed by zero or more word characters.

Also, it's a good idea to use raw strings for regular expressions to avoid hard-to-spot bugs:

r"ITEM.(?P<key>[a-zA-Z]\w*) = (?P<value>.*);"

(note the r prefix).

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

3 Comments

thanks, that has worked perfectly! I'm just starting to get my head around regex.
@H4Z3Y: I've just added a note about raw strings. I think it's a good habit to get into.
+1 for raw strings. This is such a good idea that python should really just enforce it, since that seems to be a big part of their design philosophy anyway.
1

Accepted answer is right. Minor tweaks...

  • escape the "." after ITEM to mean a "." and not just anything
  • usually a good idea to allow for more than one space (or no spaces) around the "="

    r"ITEM\.(?P<key>[a-zA-Z]\w*) *= *(?P<value>.*?) *;"

3 Comments

I think escaping the spaces just as you did with the dot is a good idea too.
Agreed the best is to replace the " *" with "\s*" ... better regex but a little less readable ... like regex is ever readable
Actually I meant \ (with the space character), but I think in the end there is indeed a lot of "space" (pun intended) for personal preference ;o). So it would become r"ITEM\.(?P<key>[a-zA-Z]\w*)\ *=\ *(?P<value>.*?) *;" (formatting removed one space :o(

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.