regex findall根据开始字符和结束字符检索子字符串

regex findall根据开始字符和结束字符检索子字符串,regex,python-2.7,Regex,Python 2.7,我有以下字符串: 6[Sup. 1e+02] 我正在尝试检索一个子字符串,其大小仅为1e+02。变量首先引用上述指定的字符串。下面是我试过的 re.findall(' \d*]', first) 您需要使用以下正则表达式: \b\d+e\+\d+\b 说明: \s+(.*?)\] Match a single character that is a “whitespace character” (ASCII space, tab, line feed, carriage return,

我有以下字符串:

6[Sup. 1e+02]
我正在尝试检索一个子字符串,其大小仅为
1e+02
。变量首先引用上述指定的字符串。下面是我试过的

re.findall(' \d*]', first)

您需要使用以下正则表达式:

\b\d+e\+\d+\b
说明:

\s+(.*?)\]

Match a single character that is a “whitespace character” (ASCII space, tab, line feed, carriage return, vertical tab, form feed) «\s+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “]” literally «\]»
  • \b
    -单词边界
  • \d+
    -数字,1或更多
  • e
    -文字
    e
  • \+
    -文字
    +
  • \d+
    -数字,1或更多
  • \b
    -单词边界

示例代码:

import re
p = re.compile(ur'\b\d+e\+\d+\b')
test_str = u"6[Sup. 1e+02]"
re.findall(p, test_str)


输出:

['1e+02']

演示


正则表达式解释:

\s+(.*?)\]

Match a single character that is a “whitespace character” (ASCII space, tab, line feed, carriage return, vertical tab, form feed) «\s+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “]” literally «\]»

@比尔盖茨:它可以更整洁,但你只提供了一个例子。我猜所有这些值都在方括号内,并且它们都位于右括号之前。如果没有,请尝试使用
\b\d+e\+\d+\b
r
-原始字符串,在构建正则表达式时不必使用双斜杠,
u
表示Unicode字符串。请查看更多详细信息。之所以选择此解决方案,是因为当字符串中的其他位置存在干扰空格时,以及如果输入字符串中有更多的
[]
而没有数字时,此解决方案也有效<代码>6[Sup.1e+02][lorem ipsum]?OP说:“我有以下字符串:
6[Sup.1e+02]