AI For Trading: Regular Expressions of NLP-3 (88)

继续学习正则表达式。

Finding Complicated Patterns

* + ? | ( )
* 表示有0到N个
+ 表示由至少1个到N个
? 表示有 0 到 1 个
Import re module
import re

# Sample text
sample_text = '''
Mt Everest: Height 8,848 m
Mt. K2: Height 8,611 m
Mt Kangchenjunga: Height 8,586 m
Mt. Lhotse: Height 8,516 m
'''

# Create a regular expression object with a regular expression 'Mt\.?'
regex = re.compile(r'Mt\.?')

# Search the sample_text for the regular expression
matches = regex.finditer(sample_text)

# Print all the matches
for match in matches:
    print(match)

打印:

<_sre.SRE_Match object; span=(1, 3), match='Mt'>
<_sre.SRE_Match object; span=(28, 31), match='Mt.'>
<_sre.SRE_Match object; span=(51, 53), match='Mt'>
<_sre.SRE_Match object; span=(84, 87), match='Mt.'>

匹配电子邮件

# Import re module
import re

# Sample text
sample_text = '''
fake_email@fake-email.edu
fakeemail43@fake_email.com
fake891_email@fakemail.gov
52fake_email@FAKE_email.com.nl
'''

# Create a regular expression object with a regular expression that can match all
# the email addresses
regex = re.compile(r'\w+@[a-zA-Z_-]+(\.[a-zA-Z_-]+)+')
# regex = re.compile(r'[a-z_0-9]+@[a-zA-Z_-]+\.[a-z]+\.?[a-z]+')

# Search the sample_text for the regular expression
matches = regex.finditer(sample_text)

# Print all the matches
for match in matches:
    print(match)

打印:

<_sre.SRE_Match object; span=(1, 26), match='fake_email@fake-email.edu'>
<_sre.SRE_Match object; span=(27, 53), match='fakeemail43@fake_email.com'>
<_sre.SRE_Match object; span=(54, 80), match='fake891_email@fakemail.gov'>
<_sre.SRE_Match object; span=(81, 111), match='52fake_email@FAKE_email.com.nl'>

为者常成,行者常至