【问题标题】:java regex string matches and multiline delimited with new linejava 正则表达式字符串匹配和多行用新行分隔
【发布时间】:2012-02-16 19:15:41
【问题描述】:

如何编写一个匹配由新行和空格分隔的多行的正则表达式?

以下代码适用于多行,但如果输入 是

String input = "A1234567890\nAAAAA\nwwwwwwww"

我的意思是 matches() 对于输入不正确。

这是我的代码:

package patternreg;

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

public class pattrenmatching {
  public static void main(String[] args) {

    String input = "A1234567890\nAAAAA";   
    String regex = ".*[\\w\\s\\w+].*";   
    Pattern p = Pattern.compile(regex,Pattern.MULTILINE); 
    Matcher m =p.matcher(input);

            if (m.matches()) {
       System.out.println("matches() found the pattern \"" 
             + "\" starting at index " 
             + " and ending at index ");
    } else {
       System.out.println("matches() found nothing");
    }
  }
}

【问题讨论】:

  • 看起来可行!给一些更具体的,会发生什么?应该发生什么?
  • 嗨 Bhushan,即使输入由换行符分隔,匹配项也应返回匹配模式假设如果输入有多个换行符 A1234567890\nAAAAA\ndddd\ndddd\nddd,匹配项返回匹配项()找到什么都没有”
  • 我复制并粘贴了您的代码并执行,我得到了这个输出:A1234567890 AAAAA*matches() 找到了从索引开始到索引结束的模式 ""

标签: java regex


【解决方案1】:

您还可以添加 DOTALL 标志以使其正常工作:

Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);

【讨论】:

  • 如果用换行符分隔,仍然匹配不会返回 true:
  • 带字符串输入 = "A1234567890";如果输入为“A1234567890/nddd”,则匹配为真,否则匹配不为真
  • 添加 DOTALL 标志和 MULTILINE 并没有为您解决问题?如果我使用两个标志 Pattern.MULTILINE | Pattern.DOTALL 编译模式,m.matches() 将为我返回 true。不过我可能误解了你的问题......
  • 哦,谢谢 mbockus,它返回 true。非常感谢我使用了错误的正则表达式
  • 没有问题!您能帮我一个忙并将这个问题标记为已回答吗?
【解决方案2】:

我相信你的问题是 .* 是贪婪的,所以它匹配字符串中的所有其他 '\n'。

如果您想坚持使用上面的代码,请尝试:“[\S]*[\s]+”。这意味着匹配零个或多个非空白字符,后跟一个或多个空白字符。

修改代码:

public static void main(String[] args) {

    String input = "A1234567890\nAAAAA\nsdfasdf\nasdfasdf";
    String regex = "[\\S]*[\\s]+";
    Pattern p = Pattern.compile(regex, Pattern.MULTILINE);

    Matcher m = p.matcher(input);

    while (m.find()) {

        System.out.println(input.substring(m.start(), m.end()) + "*");
    }

    if (m.matches()) {
        System.out.println("matches() found the pattern \"" + "\" starting at index " + " and ending at index ");
    } else {
        System.out.println("matches() found nothing");
    }

}

输出:

A1234567890 * AAAAA * sdfsdf * matches() 什么也没找到

还有一种模式

"([\\S]*[\\s]+)+([\\S])*"

将匹配整个输出(匹配器返回 true),但会弄乱代码的标记部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多