Java Pattern Class is a public final class provided in java.util package used to create compiled representation of regular expressions. All the regular expressions are converted to an instance of this class. They are used to create an instance of Matcher class, which consists of matches method that compares to get the strings that match the regular expressions and return true if the strings matches otherwise returns false. This class’s instance is immutable and is thread-safe, which means its instance has no effect with the working of different threads working concurrently.
Java Pattern Class Methods
Given below are the java pattern class methods:
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
1. public static Pattern compile (String myregex)
This method helps to create a pattern out of the given regular expression.
|
The regular expression to be compiled in the form of string.
Example:
|
PatternSyntaxException is thrown when the syntax of the expression is invalid being passed to the method.
Example:
import java.util.regex.Pattern; public class HelloWorld { private static final String MYREGEX = " ( .*) (Learn) ( .*)?"; public static void main (String[] args) { Pattern pattern = Pattern.compile (MYREGEX); System.out.println ( "Regular Expression " +pattern.pattern ()); } }
Code:
Parameters
|
a. myregex: The regular expression to be compiled in the form of string. |
b. flag: Flags are the specifications that need to be provided while compiling a regular expression. Example are CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE. |
2. public static Pattern compile (String myregex, int flag) This method helps to create the instance of Pattern class using regular expression and specified flags.
|
a. myregex: The regular expression to be compiled in the form of string. |
b. flag: Flags are the specifications that need to be provided while compiling a regular expression. Example are CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE. |
import java.util.regex.Pattern; public class HelloWorld { private static final String REGEX = " ( .*) (Learn) ( .*)?"; public static void main (String[] args) { Pattern pattern = Pattern.compile (REGEX, Pattern.CASE_INSENSITIVE); System.out.println ( "Regular Expression " +pattern.pattern ()); } }
PatternSyntaxException is thrown when the syntax of the expression is invalid being passed to the method.
IllegalArgumentException is thrown if bit values are different to the ones that match the flags that are passed.
Code:
Output:
import java.util.regex.Pattern; public class HelloWorld { private static final String REGEX = " ( .*) (Learn) ( .*)?"; public static void main (String[] args) { Pattern pattern = Pattern.compile (REGEX, Pattern.UNICODE_CHARACTER_CLASS ); System.out.println ( "Flag for UNICODE_CHARACTER_CLASS " +pattern.flags ()); Pattern pattern2= Pattern.compile (REGEX, Pattern.UNICODE_CASE ); System.out.println ( "Flag for UNICODE_CASE " +pattern2.flags ()); } }
3. public int flags ()
This method helps to get the integer value of the flag that has been set while compiling the regular expression to create the instance of pattern class.
Parameters | inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object. |
Code:
Output:
import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HelloWorld { private static final String MYREG= " ( .*) (gu)"; private static final String SEQ ="Learning regular expression helps a lot in Artificial Intelligence"; public static void main (String[] args) { Pattern pattern = Pattern.compile (MYREG, Pattern.UNICODE_CHARACTER_CLASS ); Matcher matcherObj = pattern.matcher (SEQ); if (matcherObj.find ()) { MatchResult res = matcherObj.toMatchResult (); System.out.println ( "The offset : "+res.end ()); } } }
4. public Matcher matcher (CharSequenceinputSequence)
This method is used to create an instance of a matcher object by comparing the regular expression to the given input sequence. This method requires 1 parameter to be passed, and no exception will be thrown.
Parameters | inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object. |
Parameters | inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object. |
MyRegex: The regular expression to be compiled in the form of string. |
Parameters | inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object. |
MyRegex: The regular expression to be compiled in the form of string. |
Exception:
- PatternSyntaxException is thrown when the syntax of the expression is invalid being passed to the method.
6. public String pattern ()
This method is used to get the regular expression from which the pattern instance has been compiled. This method requires no parameters to be passed as well as no exception will be thrown.
An example for this method is shown below with an example of the quote method.
7. public static String quote (String s)
This method is used to get the literal string after the pattern is resolved using the method’s flags. This method requires 1 parameter to be passed as well as no exception will be thrown.
Parameters | The string of regular expression that needs to be compiled. |
Example:
Code:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class HelloWorld { private static String myRegx = "location$"; private static String line= "The location$ office have great capacity of seats for our employess"; private static String newEx = "Bangalore"; public static void main (String[] args) { Pattern patternObj2 = Pattern.compile (Pattern.quote (myRegx)); Matcher matcherObj1 = patternObj2.matcher (line); line= matcherObj1.replaceAll (newEx); System.out.println ( "The Regular expression defined for pattern instance is " +patternObj2.pattern ()); System.out.println ( "The Input sequence after substitution of Regular Expression "+ line); } }
Output:
8. public String[] split (CharaterSequence in)
This method is used to split the input String argument at every index where regular expression is found. This method requires 1 parameter to be passed as well as no exception will be thrown.
Parameters | input: The character sequence that is to be split according to the Regular expression specified. |
Example:
Code:
import java.util.regex.Pattern; public class HelloWorld { private static String REGEX = ":"; private static String INPUT = "BANGLORE:CHENNAI:GUWAHATI:AHMEDABAD"; public static void main (String[] args) { Pattern patternObj2 = Pattern.compile (REGEX); String[] result = patternObj2.split (INPUT); for (String data:result){ System.out.println (data+"\n"); } } }
Output:
9. public String[] split (CharaterSequencein, intmyThreshHold)
This method also splits the given input sequence but upto some threshold. This method requires 2 parameters to be passed as well as no exception will be thrown.
Parameters | a. in: The character sequence that is to be split. |
b. myThreshHold: This parameter defines the threshold of splitting operation. |
Example:
Code:
import java.util.regex.Pattern; public class HelloWorld { private static String REGEX = ":"; private static String INPUT = "BANGLORE:CHENNAI:GUWAHATI:AHMEDABAD"; public static void main (String[] args) { Pattern patternObj2 = Pattern.compile (REGEX); String[] result = patternObj2.split (INPUT,3); for (String data:result){ System.out.println (data+"\n"); } } }
Output:
10. public String toString ()
This method is used to get the String representation of the regular expression from which the regular expression has been compiled. This method requires no parameters to be passed as well as no exception will be thrown.
Example:
Code:
import java.util.regex.Pattern; public class HelloWorld { private static String REGEX = "location$"; public static void main (String[] args) { Pattern patternObj2 = Pattern.compile (Pattern.quote (REGEX)); System.out.println ( "toString representation of pattern instance is " +patternObj2.toString ()); } }
Output:
Conclusion
Pattern class is used to store the compiled representation of regular expressions from where they are passed to an instance of Matcher class to get the strings that match that regular expression. In this way, one is able to work with regular expressions more efficiently in their application.
The above is the detailed content of Java Pattern Class. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools
