正则表达式是一种强大而灵活的文本处理工具。使用它我们能以编程的方式,构造复杂的文本模式,并对输入的字符串进行搜索。一旦找到了匹配这些模式的部分,你就能够随心所欲地对它们进行处理。

  关于正则表达式的语法,网上对此有介绍的文章实在是多不胜数,实在找不到,还可以查看Java的API文档,就不多介绍了。这里主要介绍一个可以测试正则表达式的小工具。直接上代码:

 1 package com.test.stringregex;
 2 //{Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}"}
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 public class TestRegularExpression {
 7     public static void main(String[] args) {
 8         if(args.length < 2) {
 9             System.out.println("Usage:\njava TestRegularExpression " +
10         "characterSequence regularExpression+");
11             System.exit(0);
12         }
13         System.out.println("Input: \"" + args[0] + "\"");
14         for(String arg : args) {
15             System.out.println("Regular expression: \"" + arg + "\"");
16             Pattern p = Pattern.compile(arg);
17             Matcher m = p.matcher(args[0]);
18             while(m.find()) {
19                 System.out.println("Match \"" + m.group() + "\" at positions " +
20                     m.start() + "-" + (m.end() - 1));
21             }
22         }
23     }
24 }
View Code

相关文章:

  • 2022-12-23
  • 2021-04-19
  • 2022-01-01
  • 2021-10-06
  • 2021-12-21
  • 2022-01-27
猜你喜欢
  • 2021-11-22
  • 2021-04-04
  • 2021-09-07
  • 2021-08-11
  • 2021-12-23
  • 2021-11-05
相关资源
相似解决方案