【问题标题】:Regex matching with pattern and matches正则表达式匹配模式和匹配
【发布时间】:2018-12-17 10:52:24
【问题描述】:

我正在从包含以下行集的文件中读取输入:

BDI100 172.20.1.5 YES TFTP up up BDI500 172.20.1.50 YES TFTP up up BDI600 172.20.1.58 YES TFTP up up

我必须提取仅包含 172.20.1.5 的完整行

下面是我的代码:

while ((line = lineNumberReader.readLine()) != null) {
        Pattern p = Pattern.compile(expr.trim()); /*expr is filter contains 172.20.1.5 */
        Matcher m = p.matcher(line);
        if(m.find()){
            System.out.println(line);
        }
    }

我将输出显示为:

BDI100                 172.20.1.5      YES TFTP   up                    up

但是正在打印所有的行。

【问题讨论】:

  • 试试这个Pattern.compile("172\\.20\\.1\\.5\\s");
  • 请注意,您可以将p 的创建(最好给变量赋予有意义的名称!不是p 和m)在循环之外。编译模式是一项昂贵的操作。
  • 对于这种情况,您是否特别需要正则表达式?只是一个简单的 contains() 可能会有所帮助?
  • 用于过滤的expr可以是172.20.1.5或BDI100

标签: java pattern-matching matcher


【解决方案1】:

这将对您有所帮助:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String[] lines = new String[]{"BDI100                 172.20.1.5      YES TFTP   up                    up",
            "BDI500                 172.20.1.50     YES TFTP   up                    up",
            "BDI600                 172.20.1.58     YES TFTP   up                    up"};
        Pattern p = Pattern.compile("172\\.20\\.1\\.5\\s");
        for (String line : lines) {
            Matcher m = p.matcher(line);
            if (m.find()) {
                System.out.println(line);
            }
        }
    }

}

【讨论】:

    【解决方案2】:

    你的所作所为似乎有点过分了。也许试试这个:

    String need = "172.20.1.5";
    String line = "";
    while ((line = lineNumberReader.readLine()) != null) {
        if (line.trim().equals("")) {
            continue:
        }
        if (line.contains(need) {
            System.out.println(line);
            break;
        }
    }
    

    【讨论】:

      【解决方案3】:
      /*Intialize expr within braces */
      String expr = "(172.20.1.5 )";
      while ((line = lineNumberReader.readLine()) != null) {
              Pattern p = Pattern.compile(expr.trim()); /*expr is filter contains 172.20.1.5 */
              Matcher m = p.matcher(line);
              if(m.find()){
                  System.out.println(line);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-06
        • 2016-04-20
        • 2014-09-15
        • 2016-04-24
        相关资源
        最近更新 更多