理解正则表达式

Kam*_*ath 2 c python regex gcc

我正在尝试解析由gcc生成的映射文件,用于函数地址.这里有一个可能的 解决方案(python),但它对我不起作用.

我试图了解提供的解决方案.它有两个复杂的正则表达式..

m = re.search('^\[([0-9 ]+)\]\s+(.+)\s*$',line )
m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+(\[([ 0-9]+)\]|\w+)\s+(.*?)\s*$', line)
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释一下RE在寻找什么?

有没有其他工作解决方案从gcc生成mapfile获取函数地址?

Wil*_*ord 10

^\[([0-9 ]+)\]\s+(.+)\s*$

^                  start of the line
\[                 literal [
([0-9 ]+)          group of 0-9 or space, one or more times
\]                 literal ]
\s+                one or more spaces
(.+)               group of anything one or moretimes
\s*                zero or more spaces 
$                  end of line


eg: "[5 5 5] blah"

gives:
    group1 = "5 5 5"
    group2 = blah

^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+(\[([ 0-9]+)\]|\w+)\s+(.*?)\s*$

^                  start of line
([0-9A-Fx]+)       group of chars one or more times
\s+                one or more spaces
([0-9A-Fx]+)       group of chars one or more times
\s+                one or more spaces
(
    \[             literal [
    ([ 0-9]+)      group of char 1 or more times
    \]             literal [
    |              or
    \w+            word char, one or more times
)
\s+                one or more spaces
(.*?)              any char zero or more times, non greedy
\s*                zero or more spaces
$                  end of line
Run Code Online (Sandbox Code Playgroud)

  • (应该注意的是,末尾的`\ s*`总是不匹配,因为`(.+)`中的`+`是贪婪的) (2认同)

Ste*_*ard 6

调试Python正则表达式的一种方法是在创建模式对象时使用未记录的re.DEBUG标志.

>>> import re
>>> re.compile('^\[([0-9 ]+)\]\s+(.+)\s*$', re.DEBUG)
at at_beginning
literal 91
subpattern 1
  max_repeat 1 65535
    in
      range (48, 57)
      literal 32
literal 93
max_repeat 1 65535
  in
    category category_space
subpattern 2
  max_repeat 1 65535
    any None
max_repeat 0 65535
  in
    category category_space
at at_end
<_sre.SRE_Pattern object at 0x01CE8950>
Run Code Online (Sandbox Code Playgroud)

这显然不是100%直接阅读,但如果您对匹配的工作方式有所了解并发现缩进有用,则可以提供帮助.