我在与一个Python正则表达式困难正则表达式结束。我想罚款任何N,S,E,W,NB,SB,EB,WB,包括字符串的开头或结尾。我的正则表达式很容易在中间找到它,但在开始或结束时都失败。麻烦匹配图案或在Python
任何人都可以建议我在做什么毛病dirPattern我下面的代码示例?
注:我知道我有一些其他的问题来处理(例如,“W的”),但想我知道如何修改正则表达式的。
在此先感谢。
import re
nameList = ['Boulder Highway and US 95 NB', 'Boulder Hwy and US 95 SB',
'Buffalo and Summerlin N', 'Charleston and I-215 W', 'Eastern and I-215 S', 'Flamingo and NB I-15',
'S Buffalo and Summerlin', 'Flamingo and SB I-15', 'Gibson and I-215 EB', 'I-15 at 3.5 miles N of Jean',
'I-15 NB S I-215 (dual)', 'I-15 SB 4.3 mile N of Primm', 'I-15 SB S of Russell', 'I-515 SB at Eastern W',
'I-580 at I-80 N E', 'I-580 at I-80 S W', 'I-80 at E 4TH St Kietzke Ln', 'I-80 East of W McCarran',
'LV Blvd at I-215 S', 'S Buffalo and I-215 W', 'S Decatur and I-215 WB', 'Sahara and I-15 East',
'Sands and Wynn South Gate', 'Silverado Ranch and I-15 (west side)']
dirMap = {'N': 'North', 'S': 'South', 'E': 'East', 'W': 'West'}
dirPattern = re.compile(r'[ ^]([NSEW])B?[ $]')
print('name\tmatch\tdirSting\tdirection')
for name in nameList:
match = dirPattern.search(name)
direction = None
dirString = None
if match:
dirString = match.group(1)
if dirString in dirMap:
direction = dirMap[dirString]
print('%s\t%s\t%s\t%s'%(name, match, dirString, direction))
一些样品预期输出:
name match dirSting direction
Boulder Highway and US 95 NB <_sre.SRE_Match object at 0x7f68af836648> N North
Boulder Hwy and US 95 SB <_sre.SRE_Match object at 0x7f68ae836648> S South
Buffalo and Summerlin N <_sre.SRE_Match object at 0x7f68af826648> N North
Charleston and I-215 W <_sre.SRE_Match object at 0x7f68cf836648> W West
Flamingo and NB I-15 <_sre.SRE_Match object at 0x7f68af8365d0> N North
S Buffalo and Summerlin <_sre.SRE_Match object at 0x7f68aff36648> S South
Gibson and I-215 EB <_sre.SRE_Match object at 0x7f68afa36648> E East
然而,开始或结束的例子给:
Boulder Highway and US 95 NB None None None
'^'和'$'*括号内*并不意味着仍然字符串的开始/结束,你知道吗? – jonrsharpe
乔恩,谢谢,我不知道,虽然我开始怀疑这一点。 –
你想要做什么?你也可以使用'direction = dirMap.get(dirString)',如果字典 –