Skip to content

Instantly share code, notes, and snippets.

@gwsu2008
Created December 10, 2017 06:22
Show Gist options
  • Save gwsu2008/44475d74b94118d43432e3ef40cb0f21 to your computer and use it in GitHub Desktop.
Save gwsu2008/44475d74b94118d43432e3ef40cb0f21 to your computer and use it in GitHub Desktop.
java string match
import java.util.*;
import java.util.regex.*;
class NumRegex
{
public static void main(String args[])
{
// Create a regular expression that matches
// any number You know all this! This is why you came here ;)
// What matches and what doesn't?
// 1 matches
// 24133242 matches
// 2342332d doesn't match (it contains d at last!)
// 23432 233 doesn't match (it contains a space)
// asdfsafd doesn't match (it is not a number)
// What's the +?
// More 1 or more than 1 digit
// \\d is for a signle digit
String numRegex="^[\\d]+$";
// This is another way, isn't it lengthy?
// Yet, remember it!
// String numRegex="^[0-9]+$";
// Hmm, one more. What if i want only a 2 digit number
// Replace 2 with whatever you no.of digits you want in
// the number.
// String numRegex="^[\\d]{2}$";
// Create a Scanner object
Scanner s=new Scanner(System.in);
// Give the regex for compilation.
// Don't worry, it gives a Pattern object in return! ;)
Pattern p=Pattern.compile(numRegex);
// Ask the user to enter a number, else he
// scratches his head of what to do!
System.out.println("Enter the number");
// Read a line, use nextLine(). If you forgot
// Line and simply use next(), you don't get spaces!
String st=s.nextLine();
// Create a Matcher, not a match box! ;)
// See if what user has given is a number!
Matcher m=p.matcher(st);
// Now, print whether the user understood what we said!
System.out.println(m.matches()?"You entered a number! Great! you understood the question :)":"I asked for number!!!!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment