【问题标题】:How to token an empty string after a word如何在单词后标记一个空字符串
【发布时间】:2014-03-31 04:33:16
【问题描述】:

我想在文本字段中输入“sin(35)”,但要计算它,我必须用空格分隔每个运算符和数字,因为我使用了 .split(""),如何将分隔符设置为是数字或运算符后的空字符串,所以它不能接受空格?

pseudocode: infix.split("" after sin | "" after [()+-*^])

【问题讨论】:

  • 我不明白你的意思,你能举个例子澄清一下吗?
  • 最后没有看到空格。你确定不能用.trim() 忽略它吗?
  • 你的意思是你想用""而不是空格分割?如果是,那是不可能的。你需要使用 substring , indexOf , ... 方法

标签: java token


【解决方案1】:

如果您只是尝试使用 split 来获取公式参数,则可以改用 PatternMatcher 类,如下所示:

String function = "";
int parameter = 0;
Pattern pattern = Pattern.compile("(sin)\\((\\d+)\\)"); // Compile the regex pattern.
Matcher matcher = pattern.matcher("sin(35)");           // Instantiate a pattern Matcher to search the string.
while (matcher.find()) {                                // For every match...
    function = matcher.group(1);                        // Get group `$1`.
    String s = matcher.group(2);                        // Get group `$2`.
    parameter = Integer.parseInt(s);                    // Parse to int, throws `NumberFormatException` if $2 is not a number.
}
System.out.println(function);                           // Prints "sin".
System.out.println(parameter);                          // Prints 35.

正则表达式:

(sin)\((\d+)\)

【讨论】:

  • 您是如何创建此图像的? :)
【解决方案2】:

你只需要一行来提取每个部分:

String function = input.replaceAll("\\(.*", "");
String parameter = input.replaceAll(".*\\(|\\).*", "");

【讨论】:

  • +1 我没有考虑简单地删除字符串中不必要的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
相关资源
最近更新 更多