python - 查找正则表达式匹配的字符串长度

标签 python regex parsing

我正在尝试编写一个脚本来解析由编译器/链接器生成的映射文件,它看起来像这样:

%SEGMENT_SECTION
                                                      Start Address  End Address
--------------------------------------------------------------------------------
Segment Name: S1_1, Segment Type: .bss                0A000000       0A050F23
--------------------------------------------------------------------------------
area1_start.o (.bss)                                  0A000000       0A000003
...

                                                      Start Address  End Address
--------------------------------------------------------------------------------
Segment Name: S2_1, Segment Type: .bss                0A050F24       0A060000
--------------------------------------------------------------------------------
area2_start.o (.bss)                                  0A000000       0A000003

...

%NEXT_SECTION

我目前正在编写几个正则表达式(python 的 re 模块)来解析它,但我想以一种非常易于阅读的方式编写它们,以便解析起来非常简单。本质上:

with open('blah.map') as f:
    text = f.read()

# ... Parse the file to update text to be after the %SEGMENT_SECTION

match = segment_header_re.match(text)
seg_name, seg_type, start_addr, end_addr = match.groups()
# ... (Do more with matched values)

text = text[len(match.matched_str):]

# Parse the remainder of text

但是,我不知道如何获取匹配字符串的长度,如我的 match.matched_str 伪代码所示。我在 python 的 re 文档中没有看到任何内容。有没有更好的方法来进行这种类型的解析?

最佳答案

对于您要实现的目标,请使用 match.span 方法。

>>> 
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> m = re.search('brown', s)
>>> m.span()
(10, 15)
>>> start, end = m.span()
>>> s[end:]
' fox jumps over the lazy dog'
>>> 

或者只是 match.end 方法。

>>> s[m.end():]
' fox jumps over the lazy dog'
>>> 

另一种选择是使用 regular expression objects它可以采用 posendpos 参数来将搜索限制在字符串的一部分。

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> over = re.compile('over')
>>> brown = re.compile('brown')
>>> m_brown = brown.search(s)
>>> m_brown.span()
(10, 15)
>>> m_over = over.search(s)
>>> m_over.span()
(26, 30)

brown 的匹配结束时开始搜索 over

>>> match = over.search(s, pos = m_brown.end())
>>> match.group()
'over'
>>> match.span()
(26, 30)

over 的匹配末尾开始搜索 brown,将不会产生匹配项。

>>> match = brown.search(s, m_over.end())
>>> match.group()

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    match.group()
AttributeError: 'NoneType' object has no attribute 'group'
>>> print(match)
None
>>> 

对于长字符串和多次搜索,使用带有起始位置参数的正则表达式对象肯定会加快速度。

关于python - 查找正则表达式匹配的字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28304320/

相关文章:

java - java中单词的简单正则表达式

javascript - JavaScript 中的电话号码格式

python - BeautifulSoup - 仅当找到特定字符串时才在标签内获取文本

python - 如何在 Pyomo 中编写分段线性目标函数

python - Pandas .filter() 属性的 Dask 等价物是什么?

python - 使用 Python 的 Vcard 解析器

javascript - 选择某个表中的范围 Cheerio

c++ - 在 C++ 中的类方法中声明类变量

php - 通过行中特定的唯一单词分割大文件,并使用 Python 或任何其他脚本语言删除这些段中的重复项

java - 在 Java 中验证来自字符串的语句