w3resource

Java: Check for a number at the end of a string


11. Check Number at End of String

Write a Java program to check for a number at the end of a string.

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("abcdef"));
		System.out.println(validate("3abcdef"));
        System.out.println(validate("abcdef9"));
		System.out.println(validate("abcdef3459"));
        }

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

Sample Output:

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

Pictorial Presentation:

Java Regular Expression: Check for a number at the end of a string.

Flowchart :

Flowchart: Check for a number at the end of a string.


For more Practice: Solve these Related Problems:

  • Write a Java program to verify that a string ends with one or more digits using a regex pattern.
  • Write a Java program to extract the numeric substring at the end of a string and return it as an integer.
  • Write a Java program to implement a method that checks for the presence of a trailing number in a given string.
  • Write a Java program to validate input strings and flag those that do not terminate with a number.

Go to:


PREV : Remove Leading Zeros from IP.

NEXT : Replace Python and Code Words.

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.