java模式正则表达式接受字符串或字符串后跟数字

时间:2016-11-19 18:25:12

标签: java regex

遇到这段代码有问题。假设接受以下输入,U,R,E,X
要么
+, - ,*,/后跟空格和数字 它必须循环,直到用户进入E来评估堆栈或队列中的任何内容

   public static void main(String[] args) {
   Scanner input = new Scanner( System.in );//scanner
   System.out.println("COMP10152 - Lab#5 - Calculator using Queues and Stacks ... by _______________ \n");
   System.out.println("Enter tokens. Legal tokens are integers, +, -, *, /, U[ndo], R[edo], E[valuate] and [e]X[it] ");
   while (!input.hasNext("[UREXurex]?[+-*/]{1}[s][0-9][1]")) {
System.out.println("Invalid Entry - Please enter operation (operator(+,-,*,/) value) or U,R,E,X");
input.next();
   }

3 个答案:

答案 0 :(得分:0)

([urexUREX]+|[\\+\\-\\*\\/]\s+\d)

这应该有用。

修改

^([urexUREX]+|[\\+\\-\\*\\/]\s[^\s]*\d+)$

这满足了所有规定的条件。

答案 1 :(得分:0)

试试这个

([UREXurex]+|[\\+\\-\\/\\*]+\\s\\d+)

编辑:

检查一下:

public static void main(String[] args) 
    {
        Scanner input = new Scanner( System.in );//scanner
           System.out.println("COMP10152 - Lab#5 - Calculator using Queues and Stacks ... by _______________ \n");
           System.out.println("Enter tokens. Legal tokens are integers, +, -, *, /, U[ndo], R[edo], E[valuate] and [e]X[it] ");
          String s;
           while (input.hasNextLine()) // Check if there is line to read
           {
               s=input.nextLine(); // read the whole line and save it.
               if(s.matches("([UREXurex]+|[\\+\\-\\/\\*]+\\s\\d+)") ) // true if the regex matches
               {
                   System.out.println("done");
               }
               else
               {
                      System.out.println("Invalid Entry - Please enter operation (operator(+,-,*,/) value) or U,R,E,X");
               }

    }

我认为问题出在hasNext()上。通常它会检查,直到遇到空间。因此,当您提供+ 2时,它会检查+。但是,当您提供正则表达式时,我不知道这种行为是否相同。

我尝试使用nextLine()代替next()来阅读该行,以防止出现上述问题。要检查正则表达式使用matches()

答案 2 :(得分:0)

由于您只有2个案例,我会将其分解为2个正则表达式并使用Java正则表达式库:

import java.util.regex.*;
...
String regex1="[UREXurex]";
String regex2="[\\+\\-\\*\\/] \\d";
Pattern p1 = Pattern.compile(regex1);
Pattern p2 = Pattern.compile(regex2);
String tokens = "";
tokens = input.nextLine();

现在你可以匹配以下两种情况:

  if(p1.matcher(tokens).matches()) {
    // process "u, r, e, x" 
  ...
  if(p2.matcher(tokens).matches()) {
    // process operator digit 
  ...
  else {
    // invalid input