关于 re.split() Python 中的正则表达式 [] vs ()
Regex [] vs () in Python with respect to re.split()
[.] 和 (,|.) 在 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']
[,\.]
等同于 ,|\.
.[1]
(,|\.)
等同于 ([,\.])
.
()
创建捕获,re.split
returns 捕获文本以及由模式分隔的文本。
>>> 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']
- 不过,当您将
|
嵌入更大的模式时,有时您可能需要 (?:,|\.)
来限制被视为 |
的操作数。
[.] 和 (,|.) 在 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']
[,\.]
等同于 ,|\.
.[1]
(,|\.)
等同于 ([,\.])
.
()
创建捕获,re.split
returns 捕获文本以及由模式分隔的文本。
>>> 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']
- 不过,当您将
|
嵌入更大的模式时,有时您可能需要(?:,|\.)
来限制被视为|
的操作数。