TransWikia.com

Matching + character with Java Regex

Stack Overflow Asked by Felix Darke on December 13, 2021

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 How to replace a plus character using Java's 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

One Answer

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;

Answered by Willis Blackburn on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP