1

I have string like this

"(length>10)&(length<100)" 

And i want this

(,length,>,10,),&,(,length,<,100,)

Is it possible get with javascript split and regex.

asked Jul 13, 2012 at 7:36
1
  • FYI, this is called tokenising or lexing. You may want to read about lexing and lexical analysers (and lexical analyser generators). Commented Jul 13, 2012 at 7:37

3 Answers 3

3
"(length>10)&(length<100)".split( /([()><&])/ ).filter( Boolean )
["(", "length", ">", "10", ")", "&", "(", "length", "<", "100", ")"]

This splits at either: (, ), >, < or & (the "or" is thanks to the [] around).

Keeping the split characters is done thanks to the capture (the parentheses around the square brackets - it's ES5 though, so not supported in IE8 and below).

Finally, to remove empty strings, I use filter( Boolean ) on the array ( ES5 too, not supported in IE8 and below either).

answered Jul 13, 2012 at 7:41
Sign up to request clarification or add additional context in comments.

Comments

2
result = subject.split(/\b|(?!\w)/);

This splits at boundaries between alphanumeric and non-alphanumeric characters, additionally between two non-alnum characters. You might get an empty match at the start/end of the string, so you need to discard zero-length results.

answered Jul 13, 2012 at 7:41

Comments

0

Instead of a split, I'd go for a global match, which behaves more like a tokenizer:

var input = "(length>10)&(length<100)";
var tokens = input.match(/\d+|[a-zA-Z]\w*|[()]|[<>=&|]+/g);

It scans the input and matches the following patterns (in order):

\d+ # one ore more digits
| # OR
[a-zA-Z]\w* # an identifier
| # OR
[()] # a single opening- or closing parenthesis
| # OR
[<>=&|]+ # one or more operators: '<=', '&', '|=', ...
answered Jul 13, 2012 at 7:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.