Python split a string w/ multiple delimiter and find the delimiter used

前端 未结 3 1480
臣服心动
臣服心动 2021-01-13 20:40

How to split string with multiple delimiters and find out which delimiter was used to split the string with a maxsplit of 1.

import re

string =\"someText:so         


        
相关标签:
3条回答
  • 2021-01-13 20:55
    string ="someText:someValue~"
    print re.split("(:|~)",string,1)
    

    If you put in group,it will appear in the list returned.You can find it from 1 index of list.

    0 讨论(0)
  • 2021-01-13 21:04

    You may use re.findall.

    >>> string ="someText:someValue~"
    >>> re.findall(r'^([^:~]*)([:~])([^:~].*)', string)
    [('someText', ':', 'someValue~')]
    
    0 讨论(0)
  • 2021-01-13 21:11

    You can use re.findall to find the none words delimiters using look around:

    >>> string ="someText:someValue~andthsi#istest@"
    >>> re.findall('(?<=\w)(\W)(?=\w)',string)
    [':', '~', '#']
    
    0 讨论(0)
提交回复
热议问题