2012-02-16 84 views
0

如何编写一个正则表达式,用于匹配多行由新行和空格定义的正则表达式?java正则表达式字符串匹配和多行用新行分隔

下面的代码适用于一个多但如果输入 是

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"); 
    } 
    } 
} 
+0

看起来像它的工作原理!给一些更具体的,会发生什么?应该发生什么? – Bhushan 2012-02-16 19:45:33

+0

嗨Bhushan,匹配应返回匹配找到的模式,即使输入由换行符分隔假设如果输入有多个换行符A1234567890 \ nAAAAA \ ndddd \ ndddd \ nddd,匹配返回匹配()什么也没有发现“ – user1182067 2012-02-16 20:08:11

+0

我复制并粘贴你的代码和执行,我得到这个输出:A1234567890 AAAAA * matches()发现模式“”从索引开始到索引 – Bhushan 2012-02-16 20:19:29

回答

0

我相信你的问题是,*是贪婪的,所以它的字符串匹配所有其它“\ 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"); 
    } 

} 

OUTPUT:

A1234567890 * AAAAA * sdfasdf *匹配()没有发现任何

而且,

图案

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

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

1

您还可以添加DOTALL标志,以得到它的工作:

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

如果用新行分隔,则仍然返回true: – user1182067 2012-02-16 20:04:02

+0

With String input = “A1234567890”;如果输入是“A1234567890/nddd”匹配不成立,则匹配成立其他明智 – user1182067 2012-02-16 20:04:50

+0

将DOTALL标志和MULTILINE一起添加并不能解决您的问题吗?m.matches()'返回true我如果我用两个标志'Pattern.MULTILINE | Pattern.DOTALL'编译模式,我可能会误解你的问题虽然... – 2012-02-16 20:08:16