代码之家  ›  专栏  ›  技术社区  ›  Crystal

模式,Java中的matcher,REGEX帮助

  •  1
  • Crystal  · 技术社区  · 16 年前

    Pattern p = Pattern.compile("(\\w+) \\1");
    StringBuilder sb = new StringBuilder(1000);
    int i = 0;
    for (String s : lineOfWords) { // line of words is a List<String> that has each line read in from txt file
    Matcher m = p.matcher(s.toUpperCase());
    // and then do something like
    while (m.find()) {
      // do something here
    }
    

    我试着查看m.end,看看是否可以创建一个新字符串,或者删除匹配项所在的项,但在阅读文档之后,我不确定它是如何工作的。例如,作为一个测试用例来了解它是如何工作的,我做了:

    if (m.find()) {
    System.out.println(s.substring(i, m.end()));
        }
    

    到包含以下内容的文本文件: This is an example example test test test.

    This is ?

    如果我有一个AraryList行words,它从一行.txt文件中读取每一行,然后我创建一个新的ArrayList来保存修改后的字符串。例如

    List<String> newString = new ArrayList<String>();
    for (String s : lineOfWords { 
       s = s.replaceAll( code from Kobi here);
       newString.add(s);
    } 
    

    2 回复  |  直到 16 年前
        1
  •  3
  •   Kobi    16 年前

    尝试以下操作:

    s = s.replaceAll("\\b(\\w+)\\b(\\s+\\1)+\\b", "$1");
    

    这个正则表达式比你的强一点-它检查整个单词(没有部分匹配),并且去掉任何数量的连续重复。
    正则表达式捕获第一个单词: \b(\w+)\b ,然后尝试匹配该单词的空格和重复: (\s+\1)+ \b \1 ,如 "for formatting" .

        2
  •  1
  •   John Kugelman Michael Hodel    16 年前

    举个例子……,所以 m.end() i m.start() 相反。

    要改进正则表达式,请使用 \b 字词前后应标明有字词界限: (\\b\\w+\\b) . 否则,正如你所看到的,你会在单词里面找到匹配。