Wednesday, June 5, 2019

Regular Expression

Java Regex

The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.


USE:
It is widely used to define the constraint on strings such as password and email validation. After learning the Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.


The java.util.regex package provides the following classes and interfaces for regular expressions.
  1. MatchResult interface
  2. Matcher class
  3. Pattern class
  4. PatternSyntaxException class


The regular expression metacharacters work as shortcodes.



RegexDescription
.Any character (may or may not match terminator)
\dAny digits, short of [0-9]
\DAny non-digit, short for [^0-9]
\sAny whitespace character, short for [\t\n\x0B\f\r]
\SAny non-whitespace character, short for [^\s]
\wAny word character, short for [a-zA-Z_0-9]
\WAny non-word character, short for [^\w]
\bA word boundary
\BA non word boundary




Q. How to Extract AllNumbers from a String ??


  1. package Java_String;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;

  4. public class ExtractAllNumbersfromString {
  5. static int finalsum=0;
  6. static String str = "ram101shyam320mohan420modi108rahul99";

  7.     public static void main(String[]args) {
  8.        
  9. //     static Pattern compile(String regex) compiles the given regex and returns the instance of the Pattern.

  10.     Pattern p = Pattern.compile("\\d+");   // ''\\d+'' regex matchcharacter Any digits, short of [0-9]

  11.        
  12. //     Matcher matcher(CharSequence input) creates a matcher that matches the given input with the pattern.
  13.     Matcher m = p.matcher(str); 
  14.        
  15.        
  16.         while(m.find()) {
  17.        
  18. //         String group() returns the matched subsequence.
  19. //             System.out.println(m.group());  // this will give number in String
  20.            
  21.             int add = Integer.parseInt(m.group()); // this will give number in Integer
  22.            
  23.             System.out.println(add);
  24.            
  25.             finalsum += add;  // this will add all group of integer number.
  26.            
  27.         }
  28.         System.out.println("Sum of all above number is  "+finalsum );
  29.     }
  30. }




No comments:

Post a Comment