Java将字符串与正则表达式进行比较-While循环 [英] Java comparing string to regex - while loop

查看:120
本文介绍了Java将字符串与正则表达式进行比较-While循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户输入一个字符串,如果该字符串与我的正则表达式不匹配,那么我希望输出一条消息,然后用户再次输入一个值.

I want the user to enter a string and if the string does not match my regex expression then I want a message to be outputted and the user to enter a value again.

问题在于,即使字符串与正则表达式匹配,它也将其视为不匹配.

The problem is even when the string matches the regex it is treating it as if it does not match.

我的正则表达式: 这应该等于-Name, Name

My regex: This should equal - Name, Name

[[A-Z][a-zA-Z]*,\s[A-Z][a-zA-Z]*]

我的while循环:

  System.out.println("Enter the student's name in the following format - surname, forename: ");  studentName = input.next();
  while (!studentName.equals("[[A-Z][a-zA-Z]*,\\s[A-Z][a-zA-Z]*]")) {
    System.out.println("try again");
    studentName = input.next();
  }

推荐答案

equals方法检查字符串是否等效,而不是匹配正则表达式.

The equals methods checks for string equivalence, not for matching regular expressions.

只需将equals替换为matches.您还应该卸下外部方括号.

Just replace equals with matches. You should also remove the outer square brackets.

这篇关于Java将字符串与正则表达式进行比较-While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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