正则表达式noob问题

2024-10-03 09:08:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的字符串:

"""$10. 2109 W. Chicago Ave., 773-772-0406, <a href="http://www.theoldoaktap.com/">theoldoaktap.com</a>"""

我知道这是一个合适的正则表达式,可以给出我想要的(输出如下):

age = re.match(r'\$([\d.]+)\. (.+), ([\d-]+)', example)
print age.groups()

output ====> ('10', '2109 W. Chicago Ave.', '773-772-0406')

但我对regex公式有一些疑问,即使在阅读了doc之后:

  1. 当用()括号分组时,这些是regex最终返回的独立元组值,对吗?你知道吗
  2. 如果我删除$符号,为什么整件事会被error:unbalanced parenthesis完全破坏呢?不管我是否事先指定了$,正则表达式不应该在$之后获取价格吗?在此基础上,如果我希望输出是10美元,而不是10美元,为什么我不能把$移到里面然后直接运行r'\($[\d.]+)?它又抛出了一个不平衡的括号错误。你知道吗
  3. 在中间的(.+),之后,逗号是python知道我们处理完要放入第二个元组值槽的值的唯一方法吗?所以,(.+)并不代表“任何角色”,是吗?如果后跟一个数字,逗号会把它移到下一个字符上,对吗?你知道吗
  4. 有人能解释一下+符号在括号内而不是在括号外的位置,以及这有什么不同吗?你知道吗

抱歉问了这么多问题。总有一天我会好起来的。提前谢谢。你知道吗


Tags: 字符串recomhttpagewww符号regex
1条回答
网友
1楼 · 发布于 2024-10-03 09:08:34

When grouped with the ()parenthesis, those are the separate tuple values the regex is ultimately returning, right?

正确

If I delete the $ sign, why does the whole thing completely break down with error:unbalanced parenthesis? shouldn't the regular expression be able to grab the price after the $ regardless of if I specified $ beforehand?

如果删除美元符号,转义符\将转义左括号字符(,请告诉正则表达式引擎不要将其视为需要在字符串中搜索的文本字符。你知道吗

after the (.+), in the middle, is the comma the only way python knows we are done with the value to be slotted into the second tuple value slot?

是的,它告诉Python在最后一个逗号之前捕获几乎所有字符中的一个或多个。.几乎可以匹配任何单个字符。.+匹配几乎所有字符中的一个或多个。你知道吗

请注意,.+是贪婪的,这意味着它将一直捕获逗号,直到最后一个逗号之前。如果您想让它在第一个逗号之前停止,可以使用.+?使它变懒

could someone explain the placement of the + signs inside the parenthesis rather than outside and how that makes a difference?

它不会改变+的行为,不管它是在内部还是外部。它只是改变了被捕获到组中的内容。你知道吗

编辑:

Why can't i move the $ inside and simply run r'($[\d.]+)? it throws me another unbalanced parenthesis error.

这是因为$也有一个特殊的含义(意思是匹配行尾),就像regex中的()一样,这意味着你需要对它进行转义,你想匹配文字字符就像对括号进行转义一样:\$。你知道吗

相关问题 更多 >