w3resource

Java: Match a string that contains only upper and lowercase letters, numbers, and underscores


8. Match Alphanumeric Underscore

Write a Java program to match a string containing only upper and lowercase letters, numbers, and underscores.

Sample Solution:

Java Code:

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
 
   public static void main(String[] args) {
	   
	    System.out.println(validate("The quick brown fox jumps over the lazy dog."));
	    System.out.println(validate("Java_Exercises_1"));
	    System.out.println(validate("Java_Exercises_11.0"));
	    System.out.println(validate("w3r"));
        }

   public static String validate(String text) {
	    Pattern pattern = Pattern.compile("^[a-zA-Z0-9_]*$");
		 Matcher m = pattern.matcher(text);
		
	   if (m.find())
                return "Found a match!";
       else
                return "Not matched!";
   }
}

Sample Output:

Not matched!
Found a match!
Not matched!
Found a match!

Pictorial Presentation:

Java Regular Expression: Match a string that contains only upper and lowercase letters, numbers, and underscores.
Java Regular Expression: Match a string that contains only upper and lowercase letters, numbers, and underscores.

Flowchart :

Flowchart: Match a string that contains only upper and lowercase letters, numbers, and underscores.


For more Practice: Solve these Related Problems:

  • Write a Java program to verify that a string contains only letters, digits, and underscores using a regular expression.
  • Write a Java program to implement a method that returns true if a string is alphanumeric with underscores and false otherwise.
  • Write a Java program to test various strings against a pattern that allows only upper/lowercase letters, numbers, and underscores.
  • Write a Java program to remove any characters from a string that are not letters, digits, or underscores.

Go to:


PREV : Match Word with Middle 'g'.
NEXT : String Starts with Specific Number.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.