拆分计算器的输入字符串 [英] Splitting input string for a calculator

查看:185
本文介绍了拆分计算器的输入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拆分用户为我的计算器给出的输入。
例如,如果用户输入23 + 45 *(1 + 1),
我想将其拆分为[23,+,45,*,(,1,+,1 ,]]。

I'm trying to split the input given by the user for my calculator. For example, if the user inputs "23+45*(1+1)" I want to this to be split into [23,+,45,*,(,1,+,1,)].

推荐答案

你所寻找的内容被称为词法分析器。您可以阅读

What your looking for is called a lexer. A lexer splits up input into chunks (called tokens) that you can read.

幸运的是,您的词法分析器是很简单,可以手写。对于更复杂的词法分析器,您可以使用 flex (as在快速词典分析器 - 而不是Adobe Flex)或(由于您使用Java) ANTLR (请注意,ANTLR不仅仅是一个词法分析器)。

Fortunately, your lexer is pretty simple and can be written by hand. For more complicated lexers, you can use flex (as in "The Fast Lexical Analyzer"--not Adobe Flex), or (since you're using Java) ANTLR (note, ANTLR is much more than just a lexer).

只需提供正则表达式列表,每个令牌匹配一个(请注意,自从输入很简单,你可以不用这个列表,并将它们全部合并成一个正则表达式,但是对于更高级的词法分析器,它有助于为每个令牌做一个正则表达式,例如

Simply come up with a list of regular expressions, one for each token to match (note that since your input is so simple, you can probably do away with this list and merge them all into one single regex. However, for more advanced lexers, it helps to do one regex for each token) e.g.

\d+
\+
-
*
/
\(
\)

然后启动一个循环:当有更多的字符被解析时,正则表达式并尝试将它们与字符串的开头进行匹配。如果匹配,请将第一个匹配的组添加到您的输入列表中。否则,继续匹配(如果没有匹配,告诉用户他们有语法错误)。

Then start a loop: while there are more characters to be parsed, go through each of your regular expressions and attempt to match them against the beginning of the string. If they match, add the first matched group to your list of input. Otherwise, continue matching (if none of them match, tell the user they have a syntax error).

伪代码:

List<String>input = new LinkedList<String>();
while(userInputString.length()>0){
    for (final Pattern p : myRegexes){
        final Matcher m = p.matcher(userInputString);
        if(m.find()) {
            input.add(m.group());
            //Remove the token we found from the user's input string so that we
            //can match the rest of the string against our regular expressions.
            userInputString=userInputString.substring(m.group().length());
            break;
        }
    }
}

实现说明:


  • 您可能希望将 ^ 字符添加到所有正则表达式中。这样可以确保您的匹配符合字符串的开头。我的伪代码假设你已经这样做了。

  • You may want to prepend the ^ character to all of your regular expressions. This makes sure you anchor your matches against the beginning of the string. My pseudocode assumes you have done this.

这篇关于拆分计算器的输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆