在Python中通过正则表达式对具有不同分隔符的字符串进行标记

问题描述 投票:0回答:3

我有另一个软件的输出字符串。如下:

tstring = "12A/Ma1 $GJG (#G25)"

我想提取一个简单的列表:

["Ma","GJG", "G25"]

特别是:

['the first two characters after the /', 'the characters after $ before the next space', 'the contents of the bracket without the #']

我尝试像在 Excel 中那样使用各种查找和匹配结构,但我觉得正则表达式是更好的选择。虽然我不知道如何构建它。

有人可以帮忙吗?

python regex
3个回答
1
投票

将输入字符串分成几部分,即要匹配的部分和中间的部分:

.*?/    # Any characters until/including the first slash
(..)    # The next two characters (as a group)
.*?\$   # Any characters until/including the next dollar sign
(\S*)   # 0 or more non-space characters (as a group)
.*\(    # Any characters until/including the last opening parenthesis
(.*)    # Any characters (as a group)
\)      # The closing parenthesis

>>> import re
>>> tstring = "12A/Ma1 $GJG (#G25)"
>>> m = re.match(r'.*?/(..).*?\$(\S*).*\((.*)\)', tstring)
>>> m.groups()
('Ma', 'GJG', '#G25')

1
投票

使用 Python 的

re
HOWTO 中的信息足以想出一个简单的正则表达式来满足您的要求。事实上,我们只是将您的匹配条件的英文描述翻译成正则表达式语法。

生成的正则表达式如下:

r"/(.{2}).*?\$(\S*).*?\(#(.*?)\)"

它使用三个捕获组,(未转义的)括号中的内容,中间用

.*?
作为填充符。
.*?
将非贪婪地匹配任何内容。这只是为了吞噬我们不感兴趣的角色。

第一个捕获组位于斜杠之后的任意两个字符。

第二个捕获组位于美元符号之后,除了空格之外的任何内容。

第三个捕获组是(转义的)括号中的任何内容,没有前导哈希。

以下小脚本将产生您要求的输出:

import re

tstring = "12A/Ma1 $GJG (#G25)"

match = re.search(r"/(.{2}).*?\$(\S*).*?\(#(.*?)\)", tstring)
if match:
    print(list(match.groups()))
else:
    print("no match")

打印:

['Ma', 'GJG', 'G25']

转换为

list
是可选的;
matches.groups()
返回一个元组,而您想要一个列表。

...或者只是分开

对于像您这样的简单示例(并且假设字符串看起来总是或多或少相同),您也可以不使用

re
模块并使用
str.split()
...好吧,多次。

这个想法是根据您描述的分隔符分割

tstring
。这对眼睛来说并不容易(但是,正则表达式有时也可能有点难看)。它仅适用于字符串和列表操作:

split_string = [
        tstring.split('/', maxsplit=1)[1][0:2],
        tstring.split('$', maxsplit=1)[1].split(' ')[0],
        tstring.split('(#', maxsplit=1)[1].split(')')[0]
]
print(split_string)

与上面相同的输出。


1
投票

不复杂,但很基本,请查看https://regex101.com/

import re
tstring = "12A/Ma1 $GJG (#G25)"
match1= re.findall("\/(..)", tstring)
match2= re.findall("\$(.*) ", tstring)
match3= re.findall("\(#(.*)\)", tstring)
print(match1[0])
print(match2[0])
print(match3[0])

结果

Ma
GJG
G25

请注意,需要一些 \ 来转义正则表达式语法字符,例如 / 或 $ 才能执行此操作。

list = [match1[0],match2[0],match3[0]]

将所有结果粘贴到列表中。

['Ma', 'GJG', 'G25']
© www.soinside.com 2019 - 2024. All rights reserved.