How do I regex split by space, avoiding spaces within apostrophes?

前端 未结 3 609
忘掉有多难
忘掉有多难 2021-01-25 12:35

I want \"git log --format=\'(%h) %s\' --abbrev=7 HEAD\" to be split into

[
  \"git\", 
  \"log\",
  \"--format=\'(%h) %s\'\",
  \"--abbrev=7\",
  \         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 13:36

    I found one possible (albeit ugly) solution in python (which also works with "):

    >>> import re
    >>> foo = '''git log --format='(%h) %s' --foo="a b" --bar='c d' HEAD'''
    >>> re.findall(r'''(\S*'[^']+'\S*|\S*"[^"]+"\S*|\S+)''', foo)
    ['git', 'log', "--format='(%h) %s'", '--foo="a b"', "--bar='c d'", 'HEAD']
    
    

提交回复
热议问题