Quantifier
|
Example
|
Description
|
?
|
X?
|
X, once or not at all
|
*
|
X*
|
X, zero or more times
|
+
|
X+
|
X, one or more times
|
{n}
|
X{n}
|
X, exactly n times
|
{n,}
|
X{n,}
|
X, at least n times
|
{n,m}
|
X{n,m}
|
X, at least n but not more than m times
|
import java.util.regex.*; import java.io.*; public class RegExHarness { public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Pattern pattern; Matcher matcher; String regex; String text; while(true){ try{ System.out.println("Enter Regular Expression"); regex = br.readLine(); pattern = Pattern.compile(regex); System.out.println("Enter the string"); text = br.readLine(); matcher = pattern.matcher(text); matcher.matches(); System.out.print("I found the text " + matcher.group()); System.out.print(" starting at index " + matcher.start()); System.out.println(" Ending at index " + matcher.end()); } catch(Exception e){ System.out.println(e); } } } }
Sample Output
Enter Regular Expression a? Enter the string a I found the text a starting at index 0 Ending at index 1 Enter Regular Expression a? Enter the string aa java.lang.IllegalStateException: No match found Enter Regular Expression a* Enter the string aaaa I found the text aaaa starting at index 0 Ending at index 4 Enter Regular Expression a*b Enter the string aab I found the text aab starting at index 0 Ending at index 3 Enter Regular Expression a+b Enter the string aab I found the text aab starting at index 0 Ending at index 3 Enter Regular Expression \d{10} Enter the string 9876543210 I found the text 9876543210 starting at index 0 Ending at index 10 Enter Regular Expression \d{5,10} Enter the string 9876 java.lang.IllegalStateException: No match found Enter Regular Expression \d{5,10} Enter the string 987654 I found the text 987654 starting at index 0 Ending at index 6 Enter Regular Expression
No comments:
Post a Comment