Home > front end >  Regex split boolean string by boolean operators
Regex split boolean string by boolean operators

Time:05-04

Is there a regex to split boolean string by boolean operator but not within quotes

example: boolean_string = "'larsen and turbo' and fullsta'ck or \"ruby\" and \"ruby or rails\""

expected output: ['larsen and turbo', and, fullsta'ck, or, ruby, and, ruby or rails]

Currently trying with below code snippet but unable to escape operators within quotes. boolean_string.split(/\b(and|or)\b/)

How do I escape and and or's within quotes.`

CodePudding user response:

This may helps you:

boolean_string = "'larsen and turbo' and fullsta'ck or \"ruby\" and \"ruby or rails\""
reg = %r{
  (?:                # outer-group to use "|" for multiple matches
    ['"]([^'"] )['"] # words inside quotes
    |([\w'] )        # other words
  )
}xm

boolean_string.scan(reg).flat_map(&:compact) # => ["larsen and turbo", "and", "fullsta'ck", "or", "ruby", "and", "ruby or rails"]
  • Related