Movatterモバイル変換


[0]ホーム

URL:


Open In App

pattern() method of thePattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method is used to get the same source expression. 

Example 1: Using the pattern() methodto check the regex pattern passed for pattern matching.

Java
// Java program to demonstrate// Pattern.pattern() methodimportjava.util.regex.*;publicclassGeeks{publicstaticvoidmain(String[]args){// create a REGEX StringStringREGEX="(.*)(for)(.*)?";// create the string in which you want// to searchStringactualString="code of Machine";// create patternPatternpattern1=Pattern.compile(REGEX);// find the regular expression of patternStringRegularExpression=pattern1.pattern();System.out.println("Pattern's RegularExpression = "+RegularExpression);}}

Output
Pattern's RegularExpression = (.*)(for)(.*)?

Syntax

public String pattern()

  • Parameters: This method does not accepts anything as parameter. 
  • Return Value: This method returns the pattern's source regular expression.  

Example 2: Using the pattern() method inconjunction with aMatcher.

Java
// Java program to demonstrate the usage of// regular expressions in pattern matchingimportjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassGeeks{publicstaticvoidmain(String[]args){// Input strings to match the regex againstStringinput1="The quick brown fox jumps over the lazy dog";Stringinput2="The quick red fox jumps over the lazy dog";// Regex pattern to match case-insensitive 'the'Stringregex="(?i)the";// Compile the regex patternPatternpattern=Pattern.compile(regex);// Create matchers for both input stringsMatchermatcher1=pattern.matcher(input1);Matchermatcher2=pattern.matcher(input2);// Find and print all matches in input1while(matcher1.find()){System.out.println("Match 1: "+matcher1.group());}// Find and print all matches in input2while(matcher2.find()){System.out.println("Match 2: "+matcher2.group());}}}

Output
Match 1: TheMatch 1: theMatch 2: TheMatch 2: the

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp