HomeContact

How to use Java Regular Expression

Published in Java
May 15, 2023
1 min read

Regular expression is used to find a string part that matches the desired condition(pattern) in the string data, and refers to a string created using predefined symbols and characters.

🌱Java Sample

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// String to compare
String txt = "number1487context";
// Regular Expression Grammar in String Form
String patternString = "^[0-9]+";
// 1) Converting regular expression grammar in the form of a string into regular expression patterns
Pattern pattern = Pattern.compile(patternString);
// 2) Examine the string with the matcher method as a pattern object and return filtered results to the matcher object
Matcher matcher = pattern.matcher(txt);
// 3) Matcher containing filtered regular expressions outputs results via method
System.out.println(matcher.find()); // Do you have a matching result? : true
System.out.println(matcher.group()); // Returns the matched part : 1487
// How to handle multiple matched results
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}

Tags

#Java#Regular

Share


Previous Article
How to do Encapsulation in Java Getter,Setter

Topics

Java
Other
Server

Related Posts

How to use BigInteger in Java - 2
May 31, 2023
1 min