开发者

Python Regex pattern not being matched

开发者 https://www.devze.com 2023-04-12 23:16 出处:网络
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

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'开发者_StackOverflow中文版;\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.


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).


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>.*?) *;"

0

精彩评论

暂无评论...
验证码 换一张
取 消