【问题标题】:Regex [] vs () in Python with respect to re.split() [duplicate]Python 中关于 re.split() 的正则表达式 [] vs () [重复]
【发布时间】:2020-10-26 02:17:01
【问题描述】:

[,.] 和 (,|.) 在 re.split(pattern,string) 中用作模式时有什么区别?有人可以解释一下这个 Python 中的例子吗:

import re
regex_pattern1 = r"[,\.]"
regex_pattern2 = r"(,|\.)"
print(re.split(regex_pattern1, '100,000.00')) #['100', '000', '00']
print(re.split(regex_pattern2, '100,000.00'))) #['100', ',', '000', '.', '00']

【问题讨论】:

  • 第一个是字符类,第二个是捕获组
  • 此页面已被关闭,因为该页面完全没有解释 split 的行为。
  • 对不起,我想我的标题不清楚,我想问的是为什么字符类和捕获组在 re.split() 方面的工作方式不同

标签: python regex split capturing-group character-class


【解决方案1】:

[,\.] 等价于,|\.[1]

(,|\.) 等价于([,\.])

() 创建一个捕获,re.split 返回捕获的文本以及由模式分隔的文本。

>>> import re
>>> re.split(r'([,\.])', '100,000.00')
['100', ',', '000', '.', '00']
>>> re.split(r'(,|\.)', '100,000.00')
['100', ',', '000', '.', '00']
>>> re.split(r',|\.', '100,000.00')
['100', '000', '00']
>>> re.split(r'(?:,|\.)', '100,000.00')
['100', '000', '00']
>>> re.split(r'[,\.]', '100,000.00')
['100', '000', '00']

  1. 不过,当您将 | 嵌入到更大的模式中时,您有时可能需要 (?:,|\.) 来限制它的操作数。

【讨论】:

  • .不需要在字符类中转义,所以可以是[,.]
猜你喜欢
  • 2016-02-08
  • 2013-10-28
  • 2020-07-01
  • 2016-12-29
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 2022-11-15
相关资源
最近更新 更多