学点Java正则表达式(3)
2008-02-23 09:15:48来源:互联网 阅读 ()
通过调用String group(int groupIndex),你可以简单地得到匹配的字符串。
第0个分组代表所有的分组,第一个实际分组的索引是1。调用groupCount来获得总的分组数。
使用开放圆括号来安排嵌套分组。例如,给定模式((1?[0-9]):([0-5][0-9]))[ap]m,并且输入11:59am,Matcher对象报告下列分组
((1?[0-9]):([0-5][0-9]))[ap]m
并输入
11:59am
matcher报告下列分组
分组索引 起始 结束 字符串
0 0 7 11;59am
1 0 5 11:59
2 0 2 11
3 3 5 59
例12-9提示输入一个模式和一个欲匹配的字符串。它将输出输入的字符串是否匹配模式。如果输入匹配包含分组的模式,程序将会使用圆括号来打印分组边界,如((11):(59))am
Example 12-9. RegexTest.java
1. import java.util.*;
2. import java.util.regex.*;
3.
4. /**
5. This program tests regular expression matching.
6. Enter a pattern and strings to match, or hit Cancel
7. to exit. If the pattern contains groups, the group
8. boundarIEs are displayed in the match.
9. */
10. public class RegExTest
11. {
12. public static void main(String[] args)
13. {
14. Scanner in = new Scanner(System.in);
15. System.out.println("Enter pattern: ");
16. String patternString = in.nextLine();
17.
18. Pattern pattern = null;
19. try
20. {
21. pattern = Pattern.compile(patternString);
22. }
23. catch (PatternSyntaxException e)
24. {
25. System.out.println("Pattern syntax error");
26. System.exit(1);
27. }
28.
29. while (true)
30. {
31. System.out.println("Enter string to match: ");
32. String input = in.nextLine();
33. if (input == null || input.equals("")) return;
34. Matcher matcher = pattern.matcher(input);
35. if (matcher.matches())
36. {
37. System.out.println("Match");
38. int g = matcher.groupCount();
39. if (g > 0)
40. {
41. for (int i = 0; i < input.length(); i )
42. {
43. for (int j = 1; j <= g; j )
44. if (i == matcher.start(j))
45. System.out.print('(');
46. System.out.print(input.charAt(i));
47. for (int j = 1; j <= g; j )
48. if (i 1 == matcher.end(j))
49. System.out.print(')');
50. }
51. System.out.println();
52. }
53. }
54. else
55. System.out.println("No match");
56. }
57. }
58. }
通常地,你不希望匹配整个输入到某个正则表达式,而是希望在输入中找出一个或多个匹配的子字符串。使用Matcher类的find方法来寻找下一个匹配。如果它返回True,再使用start和end方法找出匹配的范围。
例12-10用到了这种机制。它在一个网页中定位所有的超文本引用并打印它们。为运行程序,在命令行提供一个URL,比如
java HrefMatch http://www.horstmann.com
Example 12-10. HrefMatch.java
1. import java.io.*;
2. import java.net.*;
3. import java.util.regex.*;
4.
5. /**
6. This program displays all URLs in a Web page by
7. matching a regular expression that describes the
8. <a href=...> HTML tag. Start the program as
9. java HrefMatch URL
10. */
11. public class HrefMatch
12. {
13. public static void main(String[] args)
14. {
15. try
16. {
17. // get URL string from command line or use default
18. String urlString;
19. if (args.length > 0) urlString = args[0];
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
