forked from mthli/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegexTest.java
More file actions
58 lines (54 loc) · 1.94 KB
/
RegexTest.java
File metadata and controls
58 lines (54 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package regex;
import java.util.*;
import java.util.regex.*;
/**
This program tests regular expression matching. Enter a pattern and strings to match,
or hit Cancel to exit. If the pattern contains groups, the group boundaries are displayed
in the match.
@version 1.02 2012-06-02
@author Cay Horstmann
*/
public class RegexTest
{
public static void main(String[] args) throws PatternSyntaxException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter pattern: ");
String patternString = in.nextLine();
Pattern pattern = Pattern.compile(patternString);
while (true)
{
System.out.println("Enter string to match: ");
String input = in.nextLine();
if (input == null || input.equals("")) return;
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
System.out.println("Match");
int g = matcher.groupCount();
if (g > 0)
{
for (int i = 0; i < input.length(); i++)
{
// Print any empty groups
for (int j = 1; j <= g; j++)
if (i == matcher.start(j) && i == matcher.end(j))
System.out.print("()");
// Print ( for non-empty groups starting here
for (int j = 1; j <= g; j++)
if (i == matcher.start(j) && i != matcher.end(j))
System.out.print('(');
System.out.print(input.charAt(i));
// Print ) for non-empty groups ending here
for (int j = 1; j <= g; j++)
if (i + 1 != matcher.start(j) && i + 1 == matcher.end(j))
System.out.print(')');
}
System.out.println();
}
}
else
System.out.println("No match");
}
}
}