正则表达式java - 检查空格或字符

时间:2015-03-31 16:17:50

标签: java regex

我正在尝试编写一个正则表达式,以便在标记内出现多个空格或字符。我写了像这样的正则表达式 -

[tag:title](.*?)[tag:/title].

但是在字符串中如果有多个空格后它不匹配。如果有一个空格或字符,则匹配它。 我也试过

<title>([\\s.]*?)</title>

但它不起作用。 请帮我纠正我的正则表达式。

我的节目是 -

        public static void main(String[] args) {
        String source1;
        source1="<tag>               apple</tag>          <b>hello</b>      <tag>       orange  gsdggg  </tag>  <tag>p wfwfw   ear</tag>";

        System.out.println(Arrays.toString(getTagValues(source).toArray())); 
}


private static List<String> getTagValues(String str) {

        if (str.toString().indexOf("&amp;") != -1) 
          {   
            str = str.toString().replaceAll("&amp;", "&");// replace &amp; by &
            //  System.out.println("removed &amp formatted--" + source);
          } 


        final Pattern TAG_REGEX = Pattern.compile("<title>(.*?)</title>");
        final List<String> tagValues = new ArrayList<String>();
        final Matcher matcher = TAG_REGEX.matcher(str);
        int count=0;
        while (matcher.find()) {
            tagValues.add(matcher.group(1));
            count++;
        }
        System.out.println("Total occurance is -" + count);
        return tagValues;

}

1 个答案:

答案 0 :(得分:1)

如果您想检查多个空格,您必须使用:

\\s+

所以你的模式会变成:

([\\s+.]*/)]

或者你可以使用类似的东西:

(\\s|.)*

了解正则表达式here

您可以阅读有关字符串模式here的教程。