python - 使用正则表达式对给定的字符串进行分区

标签 python regex

尝试将字符串分成两部分。

#Need to get 'I1234' and 'I56/I78'
name1 = 'I1234/I56/I78'

#Need to get '\I1234 ' and 'I56/I78'
name2 = '\I1234 /I56/I78'      

#Need to get '\I1234 ' and '\I56 /I78'
name3 = '\I1234 /\I56 /I78'

#Need to get '\1234 ' and '\I56 /\I78 '
name4 = '\I1234 /\I56 /\I78 '

我试过了,成功了:

pat_a = re.compile(r'(.+)(/)(.+)')

Is there a better way ?

result = re.findall(pat_a, name2[::-1])

编辑

可能还有更复杂的字符串,例如:

\I78_[0]/abcd_/efg_ /I1234/I56

最佳答案

不确定是否更好,但您可以使用 partitionsplit 并设置 maxsplit=1 以避免 re 模块导入:

print('I1234/I56/I78'.partition("/"))   # ('I1234', '/', 'I56/I78')

print('I1234/I56/I78'.split("/",1))     # ['I1234', 'I56/I78']

对于 partition,您需要查看元组的第 0 个和第 2 个索引:

first, _ , last = 'I1234/I56/I78'.partition("/")

独库:


完整示例:

name1 = 'I1234/I56/I78' 
name2 = '\I1234 /I56/I78'       
name3 = '\I1234 /\I56 /I78' 
name4 = '\I1234 /\I56 /\I78 '

for n in [name1,name2,name3,name4]:
    print(n.partition("/"))   # ('I1234', '/', 'I56/I78')
    print(n.split("/",1))     # ['I1234', 'I56/I78']

输出(反斜杠被转义 - 这就是它们加倍的原因):

('I1234', '/', 'I56/I78')           # using partition
['I1234', 'I56/I78']                # using split

('\\I1234 ', '/', 'I56/I78')        # partition
['\\I1234 ', 'I56/I78']             # split .. etc.

('\\I1234 ', '/', '\\I56 /I78')
['\\I1234 ', '\\I56 /I78']

('\\I1234 ', '/', '\\I56 /\\I78 ')
['\\I1234 ', '\\I56 /\\I78 ']

关于python - 使用正则表达式对给定的字符串进行分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445651/

相关文章:

python - 使用 ctypes 从 Python 调用 fortran 函数

python - 创建具有理解力的字典?

javascript - 将句子转换为首字母大写/驼峰式大小写/正确大小写

python - 示例程序大o值

python - 像 MVC 3 这样的 flask 部分 View

python - 将逻辑门转换为 cnf python

regex - R-regex:匹配不是以模式开头的字符串

c - 后面没有数字或空格+数字的匹配词

java - 使用正则表达式 (Java) 从这些字符串中提取子字符串

python - 从文件列表中去除标点符号