【问题标题】:Need a regular expression to match a word within a multiline source [duplicate]需要正则表达式来匹配多行源中的单词[重复]
【发布时间】:2013-04-30 01:01:57
【问题描述】:

我需要一个正则表达式来匹配以下来源中的第一个单词:

WanRoutingProtocol=
     Static



              192.160.22.0/27
              false

           2004:BA2:78::50


  =IAS

我只想使用 java 中的正则表达式提取第一个单词(在本例中为“静态”)。

空白行包含多个换行符。

我正在使用以下正则表达式

  "^(\\n)+Static.*IAS"

但这不起作用。

【问题讨论】:

  • 但是第一个字是WanRoutingProtocol,不是吗?

标签: java regex


【解决方案1】:

使用以下正则表达式。表达式假定输入总是以关键字“WanRoutingProtocol”和“IAS”开始和结束,并会获取出现在“Static”位置的任何关键字。

^WanRoutingProtocol=\\s*(.*)[\\s\\w\\./:]*=IAS$

以下是在 Java 中执行此操作的方法。 (不用Pattern.MULTILINE

String input = "WanRoutingProtocol=\n" +
    "     Static\n" +
    "\n" +
    "\n" +
    "\n" +
    "              192.160.22.0/27\n" +
    "              false\n" + 
    "\n" +
    "           2004:BA2:78::50\n" +
    "\n" +
    "\n" +
    "  =IAS";
Pattern p = Pattern.compile("^WanRoutingProtocol=\\s*(.*)[\\s\\w\\./:]*=IAS$");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println(m.group(1)); // prints "Static"
}

【讨论】:

    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多