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.
- MatchResult interface
- Matcher class
- Pattern class
- PatternSyntaxException class
The regular expression metacharacters work as shortcodes.
Regex | Description |
---|---|
. | Any character (may or may not match terminator) |
\d | Any digits, short of [0-9] |
\D | Any non-digit, short for [^0-9] |
\s | Any whitespace character, short for [\t\n\x0B\f\r] |
\S | Any non-whitespace character, short for [^\s] |
\w | Any word character, short for [a-zA-Z_0-9] |
\W | Any non-word character, short for [^\w] |
\b | A word boundary |
\B | A non word boundary |
Q. How to Extract AllNumbers from a String ??
- package Java_String;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class ExtractAllNumbersfromString {
- static int finalsum=0;
- static String str = "ram101shyam320mohan420modi108rahul99";
- public static void main(String[]args) {
- // static Pattern compile(String regex) compiles the given regex and returns the instance of the Pattern.
- Pattern p = Pattern.compile("\\d+"); // ''\\d+'' regex matchcharacter Any digits, short of [0-9]
- // Matcher matcher(CharSequence input) creates a matcher that matches the given input with the pattern.
- Matcher m = p.matcher(str);
- while(m.find()) {
- // String group() returns the matched subsequence.
- // System.out.println(m.group()); // this will give number in String
- int add = Integer.parseInt(m.group()); // this will give number in Integer
- System.out.println(add);
- finalsum += add; // this will add all group of integer number.
- }
- System.out.println("Sum of all above number is "+finalsum );
- }
- }
No comments:
Post a Comment