提取名称的正则表达式

Regular Expression To Extract Names

我有这种形式的字符串:

"""00.000000 00.000000; X-XX000-0000-0; France; Paris; Street 12a;   
00.000000 00.000000; X-XX000-0000-0; Spain; Barcelona; Street 123;"""

我想获取字符串上方的特定数据 towns。我如何获得这些数据??

假设Python(三引号字符串):

string = """00.000000 00.000000; X-XX000-0000-0; France; Paris; Street 12a;   
00.000000 00.000000; X-XX000-0000-0; Spain; Barcelona; Street 123;"""

towns = [part[3] for line in string.split("\n") for part in [line.split("; ")]]
print(towns)

产生

['Paris', 'Barcelona']

不需要regex,真的。

如果您在第 4 个字段中有城市,则可以使用以下模式匹配它:

 /(?:[^;]*;){3}([^;]*);/

See the demo

[^;]*; 你找到了一个由非分号组成并以分号结尾的字段

(?:...){3}你找到了3次,但你没有捕捉到它

([^;]*); 然后你得到第 4 列匹配它的内容(不是分号)

如果您只想获取给定示例的城市,您可以使用 positive lookahead:

\b[^;]+(?=;[^;]+;$)

说明

\b        # Word boundary
[^;]+     # Match NOT ; one or more times
(?=       # Positive lookahead that asserts what follows is
   ;      # Match semicolon
   [^;]+  # Match NOT ; one or more times  
   ;      # Match ;
   $      # Match end of the string
)         # Close lookahead