Skip to content

Instantly share code, notes, and snippets.

@willstott101
Last active August 29, 2015 14:26
Show Gist options
  • Save willstott101/b97aba641d15b690d76a to your computer and use it in GitHub Desktop.
Save willstott101/b97aba641d15b690d76a to your computer and use it in GitHub Desktop.
A few simple implementations of quotable search terms splitting on whitespace.
def search_terms(s, quotes="\"'", delims='\n '):
"""
Same as shlex.split but allows for quotes to be left open.
And treats them as if they were never quoted.
"""
quote = ''
new_s = ['']
for i, c in enumerate(s, start=1):
if quote:
if c == quote:
quote = ''
new_s.append('')
else:
new_s[-1] += c
else:
if c in quotes and s.find(c, i) != -1:
quote = c
new_s.append('')
elif c in delims:
new_s.append('')
else:
new_s[-1] += c
return [s for s in new_s if s]
import shlex
def shlex_search_terms(s):
"""
Uses shlex to split a search string with quotable whitespace.
If the input has incorrect syntax the exact string is returned.
"""
try:
return shlex.split(s)
except ValueError:
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment