Author: saqibkhan

  • Java Regexs of Greedy Quantifiers

    A greedy quantifier indicates to search engine to search the entire string and check whether it matches the given regexp. Following are various examples of Greedy Quantifiers using regular expression in java.

    Sr.NoConstruct & Matches
    1X?X, once or not at all.
    2X*X, zero or more times
    3X+X, one or more times.
    4X{n}X, exactly n times.
    5X{n,}X, at least n times.
    6X{n,m}X, at least n but not more than m times
  • Examples of Boundary Matchers

    Following are various examples of Boundary Matchers using regular expression in java.

    Sr.NoConstruct & Matches
    1^The beginning of a line.
    2$The end of a line.
    3\bA word boundary.
    4\BA non-word boundary.
    5\AThe beginning of the input.
    6\GThe end of the previous match.
    7\ZThe end of the input but for the final terminator, if any.
    8\zThe end of the input.
  • Unicode Character Classes

    Following are various examples of matching Unicode character classes using regular expression in java.

    Sr.NoConstruct & Matches
    1\p{IsLatin}A Latin script character.
    2\p{InGreek}A character in the Greek block.
    3\p{Lu}An uppercase letter.
    4\p{IsAlphabetic}An alphabetic character (binary property).
    5\p{Sc}A currency symbol.
    6\P{InGreek}Any character except one in the Greek block.
    7[\p{L}&&[^\p{Lu}]]Any letter except an uppercase letter.
  • JAVA Character Classes

    Following are various examples of matching JAVA character classes using regular expression in java.

    Sr.NoConstruct & Matches
    1\p{javaLowerCase}Equivalent to java.lang.Character.isLowerCase().
    2\p{javaUpperCase}Equivalent to java.lang.Character.isUpperCase().
    3\p{javaWhitespace}Equivalent to java.lang.Character.isWhitespace().
    4\p{javaMirrored}Equivalent to java.lang.Character.isMirrored().
  • POSIX Character Classes

    Following are various examples of matching POSIX character classes using regular expression in java.

    Sr.NoConstruct & Matches
    1\p{Lower}A lower-case alphabetic character: [a-z].
    2\p{Upper}An upper-case alphabetic character:[A-Z].
    3\p{ASCII}All ASCII:[\x00-\x7F].
    4\p{Alpha}An alphabetic character:[\p{Lower}\p{Upper}].
    5\p{Digit}A decimal digit: [0-9].
    6\p{Alnum}An alphanumeric character:[\p{Alpha}\p{Digit}].
    7\p{Punct}Punctuation: One of !”#$%&'()*+,-./:;<=>?@[\]^_>{|}<.
    8\p{Graph}A visible character: [\p{Alnum}\p{Punct}].
    9\p{Print}A printable character: [\p{Graph}\x20].
    10\p{Blank}A space or a tab: [ \t].
    11\p{XDigit}A hexadecimal digit: [0-9a-fA-F].
    12\p{Space}A whitespace character: [ \t\n\x0B\f\r].
  • Predefined Character Classes

    Following are various examples of matching predefined character classes using regular expression in java.

    Sr.NoConstruct & Matches
    1.Any character (may or may not match line terminators).
    2\dA digit: [0-9].
    3\DA non-digit: [^0-9].
    4\sA whitespace character: [ \t\n\x0B\f\r]
    5\SA non-whitespace character: [^\s].
    6\wA word character: [a-zA-Z_0-9].
    7\WA non-word character: [^\w]
  • Matching Character Classes

    Following are various examples of matching character classes using regular expression in java.

    Sr.NoConstruct & Matches
    1[abc]a, b, or c (simple class).
    2[^abc]Any character except a, b, or c (negation).
    3[a-zA-Z]a through z or A through Z, inclusive (range).
    4[a-d[m-p]]a through d, or m through p: [a-dm-p] (union).
    5[a-z&&[def]]d, e, or f (intersection).
    6[a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)
    7[a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction).
  • Examples Matching Characters

    Following are various examples of matching characters using regular expression in java.

    Sr.NoConstruct & Matches
    1xThe character x
    2\\The backslash character
    3\0nThe character with octal value 0n (0 ≤ n ≤ 7)
    4\0nnThe character with octal value 0nn (0 ≤ n ≤ 7)
    5\0mnnThe character with octal value 0mnn (0 ≤ m ≤ 3, 0 ≤ n ≤ 7)
    6\xhhThe character with hexadecimal value 0xhh
    7\uhhhhThe character with hexadecimal value 0xhhhh
    8\tThe tab character (‘\u0009’)
    9\nThe newline (line feed) character (‘\u000A’)
    10\rThe carriage-return character (‘\u000D’)
    11\fThe form-feed character (‘\u000C’)
  • PatternSyntaxException 

    Introduction

    The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

    Class declaration

    Following is the declaration for java.util.regex.PatternSyntaxException class −

    public class PatternSyntaxException
       extends IllegalArgumentException
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Constructors

    Sr.NoMethod & Description
    1PatternSyntaxException(String desc, String regex, int index)Constructs a new instance of this class.

    Class methods

    Sr.NoMethod & Description
    1String getDescription()Retrieves the description of the error.
    2int getIndex()Retrieves the error index.
    3String getMessage()Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.
    4String getPattern()Retrieves the erroneous regular-expression pattern.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.lang.Throwable
    • Java.lang.Object

    Example

    The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods.

    package com.tutorialspoint;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.regex.PatternSyntaxException;
    
    public class PatternSyntaxExceptionDemo {
       private static String REGEX = "[";
       private static String INPUT = "The dog says meow " + "All dogs say meow.";
       private static String REPLACE = "cat";
    
       public static void main(String[] args) {
    
      try{
         Pattern pattern = Pattern.compile(REGEX);
         
         // get a matcher object
         Matcher matcher = pattern.matcher(INPUT); 
         INPUT = matcher.replaceAll(REPLACE);
      } catch(PatternSyntaxException e){
         System.out.println("PatternSyntaxException: ");
         System.out.println("Description: "+ e.getDescription());
         System.out.println("Index: "+ e.getIndex());
         System.out.println("Message: "+ e.getMessage());
         System.out.println("Pattern: "+ e.getPattern());
      }
    } }

    Let us compile and run the above program, this will produce the following result −

    PatternSyntaxException: 
    Description: Unclosed character class
    Index: 0
    Message: Unclosed character class near index 0
    [
    ^
    Pattern: [
    
  • Matcher Class

    Introduction

    The java.util.regex.Matcher class acts as an engine that performs match operations on a character sequence by interpreting a Pattern.

    Class declaration

    Following is the declaration for java.util.regex.Matcher class −

    public final class Matcher
       extends Object
    
      implements MatchResult

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.NoMethod & Description
    1Matcher appendReplacement(StringBuffer sb, String replacement)Implements a non-terminal append-and-replace step.
    2StringBuffer appendTail(StringBuffer sb)Implements a terminal append-and-replace step.
    3int end()Returns the offset after the last character matched.
    4int end(int group)Returns the offset after the last character of the subsequence captured by the given group during the previous match operation.
    5boolean find()Attempts to find the next subsequence of the input sequence that matches the pattern.
    6boolean find(int start)Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.
    7String group()Returns the input subsequence captured by the given group during the previous match operation.
    8String group(String name)Returns the input subsequence captured by the given named-capturing group during the previous match operation.
    9int groupCount()Returns the number of capturing groups in this matcher’s pattern.
    10boolean hasAnchoringBounds()Queries the anchoring of region bounds for this matcher.
    11boolean hasTransparentBounds()Queries the transparency of region bounds for this matcher.
    12boolean hitEnd()Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
    13boolean lookingAt()Attempts to match the input sequence, starting at the beginning of the region, against the pattern.
    14boolean matches()Attempts to match the entire region against the pattern.
    15Pattern pattern()Returns the pattern that is interpreted by this matcher.
    16static String quoteReplacement(String s)Returns a literal replacement String for the specified String.
    17Matcher region(int start, int end)Sets the limits of this matcher’s region.
    18int regionEnd()Reports the end index (exclusive) of this matcher’s region.
    19int regionStart()Reports the start index of this matcher’s region.
    20String replaceAll(String replacement)Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
    21String replaceFirst(String replacement)Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.
    22boolean requireEnd()Returns true if more input could change a positive match into a negative one.
    23Matcher reset()Resets this matcher.
    24Matcher reset(CharSequence input)Resets this matcher with a new input sequence.
    25int start()Returns the start index of the previous match.
    26int start(int group)Returns the start index of the subsequence captured by the given group during the previous match operation.
    27MatchResult toMatchResult()Returns the match state of this matcher as a MatchResult.
    28String toString()Returns the string representation of this matcher.
    29Matcher useAnchoringBounds(boolean b)Sets the anchoring of region bounds for this matcher.
    30Matcher usePattern(Pattern newPattern)Changes the Pattern that this Matcher uses to find matches with.
    31Matcher useTransparentBounds(boolean b)Sets the transparency of region bounds for this matcher.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.lang.Object