Reputation: 9417
I have the following string...
'(!false >=stuff 300 OR 200 "TEST DATA")'
I figure out how to preserve quoted text using the following...
test.match(/\w+|"[^"]+"/g)
However, the output is not what I want...
[ 'false', 'stuff', '300', 'OR', '200', '"TEST DATA"' ]
There is a list of symbols I need to preserve...
{'<', '>', '<=', '=>', '=', '!'}
so that my split should look as follows...
['(', '!', 'false', '>=', 'stuff', '300', 'OR', '200', '"TEST DATA"', ')']
How can I add onto my match
function to preserve the following? I'm not very good with regex
.
Upvotes: 0
Views: 48
Reputation: 785186
You may use:
let str = '(!false >=stuff 300 OR 200 "TEST DATA")'
let arr = str.match(/"[^"]*"|[<>]=|[^\w\s]|\w+/g)
console.log(arr)
//=> ["(", "!", "false", ">=", "stuff", "300", "OR", "200", ""TEST DATA"", ")"]
Regex has following alternatives:
"[^"]*"
: Match a quoted string[<>]=
: Match <=
or >=
[^\w\s]
: Match any non-space, non-word character\w+
: Match any wordUpvotes: 1