A regex is a string of text that allows you to create patterns that help match, locate, and manage text.For Example A+ means any number occurrence of latter A.
In Programming language we used regex when we want to Check whether text contain particular combination of character,number or symbols etc.
Here we Learn How we use regex in java to match text.
Java Provide import java.util.regex.* package for regex functionality in our application.Before going forward we consider
if (textString.matches(regexPattern)) { // it matched... do something with it... }
Here textString matches with regexPattern if it match then we perform over functionality otherwise not.
First We consider Pattern Class in java It contain compile version of regular expression. It have no constructor we called it static method compile() which generate compile version of regular expression.
Second We consider Matcher Class which compare input String with regular expression It also have no constructor.
Below is Example of Regex in Java.
package com.kodemaker; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class RegexPatternDemo { public static void main(String[] argv) throws PatternSyntaxException { String pattern = "^[0-9]*$"; String inputNumber = "123"; String inputCharcter = "a23"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(inputNumber); if(m.matches()){ System.out.println("Pattern match"); } m = p.matcher(inputCharcter); if(!m.matches()){ System.out.println("Pattern Not matched"); } } }
Output-
Pattern match
Pattern Not matched
No comments:
Post a Comment