Help with string.matches() in java

  • Comp Sci
  • Thread starter kirkulator
  • Start date
  • Tags
    Java
In summary, the user has input for the last name to be set in a method. The method checks for valid characters and throws an exception if invalid ones are found. However, the user noticed that the exception is not being caught when testing with illegal input. After some help and suggestions, it was discovered that the regex pattern needed a "+" at the end to match one or more occurrences of the valid characters. The user thanks everyone for their assistance and apologizes for any formatting issues with their code.
  • #1
kirkulator
33
0
I have input from the user which is the last name, sent to be set as the last name for my object in my setLasttName method.

public void setLastName(String lName) throws IllegalArgumentException {
if (lName.matches("[a-zA-z'-]")) {
this.lastName = lName; }
else {
throw new IllegalArgumentException("Invalid Input: name can"
+ "only consist of letters, hyphens, or apostrophes. ");
}

now, i am only aloud to have a-z, A-Z, hyphens, and apostrophes in the name, else i throw an exception. I have run this with putting '++' and other illegal input for lastname and it WILL NOT CATCH the exception, it continues with the program. what am i doing wrong? i have searched online forever trying to find a simple way to do this. is there an easier way that will work? Thanks so much! Last project of the quarter ^.^
-Amanda
 
Physics news on Phys.org
  • #2
Use [ code ] and [ /code ] tags around your code (without the spaces) to preserve indentation. I have done this for you.
kirkulator said:
I have input from the user which is the last name, sent to be set as the last name for my object in my setLasttName method.
Code:
public void setLastName(String lName) throws IllegalArgumentException {
        if (lName.matches("[a-zA-z'-]")) {
        this.lastName = lName; }
        else {
            throw new IllegalArgumentException("Invalid Input: name can"
                    + "only consist of letters, hyphens, or apostrophes. ");
        }

now, i am only aloud to have a-z, A-Z, hyphens, and apostrophes in the name, else i throw an exception. I have run this with putting '++' and other illegal input for lastname and it WILL NOT CATCH the exception, it continues with the program. what am i doing wrong? i have searched online forever trying to find a simple way to do this. is there an easier way that will work? Thanks so much! Last project of the quarter ^.^
-Amanda

I think it might be the ' character that is causing problems. See if this makes a difference: ["a-zA-Z\'-]"
 
  • #3
Some comments:
  • Your character ranges include the range A-z. You probably meant A-Z (capital z).
  • The matches method tries to match the whole string to the pattern so you would probably want to use a pattern like "[a-zA-Z'-]+" where the last + means "one or more" of the preceding pattern.
  • You say that you cannot get your code to throw IllegalArgumentException? If so, perhaps you are blind-catching the exception at some point. Check with a debugger or with debug logging that you enter the second branch of the test, or write a small unit test that calls your setter directly and checks for IllegalArgumentException.
 
  • #4
Thanks so much guys! The "+" at the end is what i needed. I'm not very familiar with the regex stuff. It seems every time i have a problem with code working its a dumb overlooking mistake. Also, thanks for the heads up on indentation! I apologize, I've never had to put code in this forum before. : )
 
  • #5


Hello Amanda,

Thank you for reaching out for help with your program. It seems like you have the right idea with using the string.matches() method to validate the input for the last name. However, there may be an issue with your regular expression pattern.

The pattern you are using, "[a-zA-z'-]", only allows for one character to be matched. This means that if the user inputs a string of multiple characters, the pattern will not match and the exception will not be thrown. To fix this, you can use the "+" symbol after the character set to indicate that you want to match one or more characters. So your pattern should be "[a-zA-Z'-]+".

Additionally, you may want to consider using the "^" and "$" symbols at the beginning and end of your pattern to indicate that you want to match the entire string and not just a part of it.

I hope this helps with your project. Good luck with the rest of the quarter!
 

1. How do I use string.matches() in Java?

To use string.matches() in Java, you first need to create a String object and assign it a value. Then, you can use the matches() method on that String object to check if it matches a specific regular expression. The syntax for using this method is:
boolean matches(String regex)
where regex is the regular expression you want to match the string against. The method returns a boolean value, true if the string matches the regex and false if it doesn't.

2. What is a regular expression?

A regular expression, also known as regex, is a sequence of characters that defines a specific search pattern. It is used to find and manipulate text based on certain patterns. In Java, regular expressions are represented by the java.util.regex.Pattern class and can be used with the matches() method to check if a string matches the specified pattern.

3. How do I write a regular expression for string.matches() in Java?

To write a regular expression for string.matches() in Java, you can use special characters and patterns to define the search pattern. Some of the commonly used characters and patterns are:

  • . - matches any single character
  • ^ - matches the beginning of a string
  • $ - matches the end of a string
  • * - matches zero or more occurrences of the previous character
  • + - matches one or more occurrences of the previous character
  • [ ] - matches any character inside the brackets
  • | - matches either the expression before or after the pipe symbol
There are many more characters and patterns that you can use to create a regular expression. It is recommended to refer to the Java documentation or online resources for a more comprehensive list.

4. Can I use string.matches() to check for multiple patterns?

Yes, you can use string.matches() to check for multiple patterns by using the | symbol. For example, if you want to check if a string contains either "apple" or "banana", you can use the regular expression "apple|banana" in the matches() method. This will return true if the string contains either of the words.

5. What is the difference between string.matches() and string.contains() in Java?

The main difference between string.matches() and string.contains() in Java is the type of argument they take. The matches() method takes a regular expression as an argument, while the contains() method takes a simple string as an argument. The matches() method is more powerful as it allows you to define complex search patterns, while the contains() method is more straightforward and only checks if a string contains a specific substring.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
6K
Back
Top