Skip to content

Instantly share code, notes, and snippets.

@adam12
Last active October 23, 2024 16:19
Show Gist options
  • Save adam12/0b3539641a7294a2b43d4ad1d951ee36 to your computer and use it in GitHub Desktop.
Save adam12/0b3539641a7294a2b43d4ad1d951ee36 to your computer and use it in GitHub Desktop.
require "strscan"
string = "aaa bbb ccc/'ddd eee/fff ggg' hhh/jjj 'kkk lll'"
class Scanner
def initialize(string)
@scanner = StringScanner.new(string)
end
def scan
matches = []
inside_quote = false
current = ""
until @scanner.eos?
ch = @scanner.getch
case ch
when "'"
inside_quote = !inside_quote
current << ch
when " "
if inside_quote
current << ch
else
matches << current
current = ""
end
else
current << ch
end
end
matches << current
matches
end
end
pp Scanner.new(string).scan
pp ["aaa", "bbb", "ccc/'ddd eee/fff ggg'", "hhh/jjj", "'kkk lll'"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment