如何使用regex只隔离字符串中的第一个空格?

2024-10-04 09:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本从外语到英语的词典,我正试图把它导入sql数据库。此词典位于文本文件中,行如下所示:

field1 field2 [romanization] /definition 1/definition 2/definition 3/

我在python中使用regex来标识分隔符。到目前为止,除了字段1和字段2之间的空格外,我已经能够隔离所有分隔符。你知道吗

(?<=\S)\s\[|\]\s/(?=[A-Za-z])|/
#(?<=\S)\s\[  is the opening square bracket after field 2
#\]\s/(?=[A-Za-z]) is the closing square bracket after the romanization
#/ is the forward slashes in-between definitions.
#????????? is the space between field 1 and field two

Tags: thefieldsqlisbetween词典分隔符square
2条回答

您可以尝试this regex,它隔离了所有字段和分隔符:

import re

preg = re.compile(r'^(?P<field1>\S+)(?P<delim1>\s+)'
                  r'(?P<field2>\S+)(?P<delim2>\s+)'
                  r'\[(?P<romanization>\S+)\](?P<delim3>\s+)'
                  r'/(?P<def1>[^/]+)/(?P<def2>[^/]+)/(?P<def3>[^/]+)')
lines = ['field1 field2 [romanization] /def 1/def 2/def 3/',
         'Foo Bar  [Foobar]\t/stuff/content/nonsense/']

for line in lines:
    m = preg.match(line)
    if m is not None:
        print(m.groupdict())

例如,您的第一个分隔符将位于m.group('delim1')。你知道吗

如果Python支持\K构造,这将起作用。
这个构造是一个变长lookback的穷人版本。你知道吗

 # (?m)(?:^[^\s\[\]/]+\K\s|(?<=\S)\s\[|\]\s/(?=[A-Za-z])|/)

 (?m)
 (?:
      ^ [^\s\[\]/]+ 
      \K 
      \s 
   |  
      (?<= \S )
      \s \[
   |  
      \] \s /
      (?= [A-Za-z] )
   |  
      /
 )

显然,Python没有这个构造,但可能支持
可变长度lookback's及其实验regex模块。你知道吗

http://pypi.python.org/pypi/regex

 # (?m)(?:(?<=^[^\s\[\]/]+)\s|(?<=\S)\s\[|\]\s/(?=[A-Za-z])|/)

 (?m)
 (?:
      (?<= ^ [^\s\[\]/]+ )
      \s 
   |  
      (?<= \S )
      \s \[
   |  
      \] \s /
      (?= [A-Za-z] )
   |  
      /
 )

相关问题 更多 >