匹配字符 + 使用Java正则表达式

huangapple go评论103阅读模式
英文:

Matching + character with Java Regex

问题

我正在编写一个程序来验证社会保障号码。我使用的是格式为YYMMDD-XXXX的10位数字,并且我需要验证日期是否正确。

如果一个人已经满100岁,那么“-”字符会被替换为“+”,我需要识别出这一点。

我正在使用equals()方法来实现这个目标,根据https://stackoverflow.com/questions/610333/how-to-replace-a-plus-character-using-javas-string-replaceall-method 的说法,我应该能够通过"\\+"来识别加号。

然而,以下方法仍然返回false:

public static boolean is100(String sweID) {
  if ((sweID.substring(6,7)).equals("\\+")) {
    return true;
  } else {
    return false;
  }
}

我知道针对这个特定问题的明显解决方法:我可以简单地编写一个正则表达式来识别“-”字符,因为那不是一个特殊字符。然而,我很好奇为什么我不能使这个方法起作用。

最好的问候,
Felix

英文:

I am writing a program to verify social security ID:s. I am working with 10 digits in the format YYMMDD-XXXX, and I need to verify if the dates are correct.

If a person is turning 100 years old, the "-" character is replaced with "+", and I need to identify this.

I am using the equals() method to achieve this goal, and according to https://stackoverflow.com/questions/610333/how-to-replace-a-plus-character-using-javas-string-replaceall-method , I should be able to identify the plus sign using "\\+".

However, the following method still returns false:

  public static boolean is100(String sweID) {
    if ((sweID.substring(6,7)).equals("\\+")) {
      return true;
    } else {
      return false;
    }
  }

I am aware of the obvious workaround for this particular: I could simply write a Regex that identifies the "-" character instead, since that is not a special character. However, I am curious to why I am not able to make this work.

Best regards
Felix

答案1

得分: 2

你正在将字符串中的第7个字符与字符串\+进行比较。这里没有正则表达式。你正在使用常规的String.equals方法,所以你可以直接传递字符串+

或者这样写也可以:

sweID.charAt(6) == '+';

另外,代替这种写法:

if (condition)
    return true;
else
    return false;

你可以直接写成:

return condition;
英文:

You're comparing the 7th character in the string with the string \+. There are no regular expressions here. You're using the regular String.equals method so you can just pass it the string +.

Or this would work:

sweID.charAt(6) == '+'

Also, instead of

if (condition)
    return true;
else
    return false;

you can just do

return condition;

huangapple
  • 本文由 发表于 2020年7月23日 23:19:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63057620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定