2012-11-06 2 views
3

문자열을 공백으로 3 개의 요소로 분할하고 싶지만 따옴표로 묶은 부분 문자열을 분할하지 마십시오 (따옴표를 이스케이프 처리하기 위해 백 슬래시를 포함 할 수도 있음). 예를 들어인용 부호가있는 부분 문자열을 보존하여 N 개의 요소를 공백으로 분할하십시오.

:

"command argument other arguments and options" 
>> ['command', 'argument', 'other arguments and options'] 

'command "my argument" other arguments and options' 
>> ['command', 'my argument', 'other arguments and options'] 

'command "my \"ugly\" argument" other "arguments" and options' 
>> ['command', 'my "ugly" argument', 'other "arguments" and options'] 

나는이 similar question에보고했지만, shlex.split()은 문자열의 끝을 분할합니다 (그것은 따옴표와 공백을 제거합니다) 나는 세 번째 요소를 유지하려는 반면, 손대지 않은.

처음 두 요소를 얻기 위해 shlex.split(mystring)[0:2]을 사용하려고했지만 원래 문자열에서 세 번째 요소를 추출하는 좋은 솔루션을 찾을 수 없습니다. 사실 나는 maxsplit 인수와 함께 str.split() 메소드와 같은 shlex.split()을 사용할 수 있기를 바랍니다.

shlex.split()을 사용하는 것보다 더 효과적인 방법이 있습니까? 아마도 정규 표현식인가? 감사!

답변

5

당신은 해킹 할 수 있어야한다 shlex 파서 객체의 상태에 액세스하여 용액 :

>>> import shlex 
>>> s = shlex.shlex("command 'my \'ugly\' argument' other \"arguments\" and options", posix=True) 
>>> s.whitespace_split = True 
>>> s.commenters = '' 
>>> next(s) 
'command' 
>>> next(s) 
'my ugly argument' 
>>> s.instream.read() 
'other "arguments" and options' 

shlex.py 모듈은 소스 참조.

+0

대단히 고마워요! – Nicolas

1

나머지 인수를 shlex으로 분할 한 후 왜 다시 가입하지 않으시겠습니까?

command = command[:2] + [' '.join(command[2:])] 

또는, shlex.shlex() 예를 직접 운전해야 할 것 :

>>> import shlex 
>>> input = "command 'my \'ugly\' argument' other \"arguments\" and options" 
>>> lex = shlex.shlex(input, posix=True) 
>>> lex.whitespace_split=True 
>>> lex.commenters = '' 
>>> command = [lex.next(), lex.next(), lex.instream.read()] 
>>> command 
['command', 'my ugly argument', 'other "arguments" and options'] 

.instream 속성은 텍스트를 들고 파일 - 류의 객체가 해석되는, 따라서 구문 분석 한 후 나머지를 포함합니다 처음 두 인수.

당신이 렉서 저장 그것을 살펴했다하지만 현재 토큰에 필요하지 않은 토큰 경우, 비록 푸시 백 상태에 액세스 할 필요가있다 :

>>> command = [lex.next(), lex.next(), ''.join(list(lex.pushback)) + lex.instream.read()] 
+1

첫 번째 해결책을 시도했지만 shlex.split()도 나머지 인수/옵션을 변경합니다 (예 : 따옴표 또는 공백을 제거). 편집 : 두 번째 예상대로 작동합니다, 감사! – Nicolas

관련 문제