How to Check if a String Only Contains Alphabet Letters in Java

Save

The most straight-forward way to check a Java string to see if it matches a set requirement for valid characters, such as only alphabetical or only alphanumeric, would be to set up a for-loop and check every individual character in the string to see if it matches the known letters of the alphabet. Fortunately, there is a better way by using a popular tool known as "regular expressions." This industry standard language of text patterns is supported by Java as a way to perform sophisticated pattern matching and parsing, and it turns what would be a tedious task into something almost trivial.

  • Open the Netbeans Integrated Development Environment (IDE) that came with your version of Java or any other Java editor you prefer.

  • Type the following text into Netbeans to define a string:

    String s1 = "This is a $tring that does not contain 0nly alphab3t1cal charact3rs.";

  • Type the following to define a regex pattern to search for:

    String pattern = "[a-zA-Z]*"

    The square brackets in a regex pattern allow you to define an entire set of valid characters, and the "*" says that you want as many of those characters as you can get. In this case, the full alphabet, both upper and lower case, is defined as valid characters, while numbers and punctuation are not.

  • Type the following command to see if the two match:

    s1.matches(pattern);

    This will return "false," since the original string contains many numbers and punctuation symbols.

Tips & Warnings

  • You could add numbers to the pattern of valid characters by simply placing "0-9" into the square brackets in Step 3. Punctuation is a little more difficult, however, since most punctuation marks have a special meaning in the regex language. Unfortunately, regex, like Java itself, is a complex language that takes a great deal of time and effort to learn. You can read more about it at the first resource.

References

Promoted By Zergnet

Comments

Resources

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!