我有以下字符串<=10 & <20
,我想拆分此字符串,以便它提供以下结果('<=' '10' '<' '20')
&amp;是无关紧要的,因为我在我的代码的不同区域处理它!感谢
答案 0 :(得分:4)
您可以使用正则表达式。您问题的可能示例:
"<=10 & <20".match(/(([<=>]+)|(\d+))/g)
完全返回您需要的内容:
["<=", "10", "<", "20"]
当然,最终的正则表达式取决于你的字符串可能具有的运算符
如果您还需要支持负值,可以将表达式更改为:
"<=10 & <-20".match(/(([<=>]+)|(-?\d+))/g)
结果:
["<=", "10", "<", "-20"]
答案 1 :(得分:1)
好像你不想像编译器那样对字符串进行标记。如果您已经参加过计算机科学课程,那么您应该了解Lexical Analysis。简而言之,您需要一台State Machine以灵活的方式对字符串进行标记。我没有看到解决这一要求的另一种方式。
只是对算法的一瞥:
var tokens = new Array();
var inputStr ...;
... a lot of state variables
var currentState = LexicalAnalysisStates.START;
for (var i = 0; i < inputStr.length; i++) {
var nextChar = input.charAt(i);
switch (currentState) {
case LexicalAnalysisStates.START: ...; // process nextChar considering START state
case LexicalAnalysisStates.DIGIT: ...; // process nextChar considering DIGIT state
case LexicalAnalysisStates.EQUAL: ...; // process nextChar considering EQUAL state
}
}
... here you should have your token collection populated
提示:首先绘制最终状态机的草图,如this one
编辑:在Artem的评论之后将代码更新为Javascript语法。
答案 2 :(得分:0)
这是你想要做的吗?
var str;
str = '<=10';
str.match(/([^0-9]+)([0-9]+)/); // ["<=10", "<=", "10"]
str = '<20';
str.match(/([^0-9]+)([0-9]+)/); // ["<20", "<", "20"]
答案 3 :(得分:0)
这应该是你应该做的事情(确保>=
<=
>
<
的正确语法:
"<=10 & <20".match(/(<|>)=?|(\d+)/g);//["<=", "10", "<", "20"]