For Testing
For Testing

Reputation: 421

Regex java - check either space or character

I am trying to write a regex for occurrence of either multiple spaces or characters within the tag. I wrote regex like this-

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

But in the string if there are multiple spaces after it doesn't match it. If there is a single space or character it matches it. I also tried

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

but it doesn't work. Please help me to correct my regex.

My program is -

        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;

}

Upvotes: 0

Views: 149

Answers (1)

James
James

Reputation: 469

If you want to check for multiple spaces your must you use:

\\s+

So your pattern will become:

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

Or you could use something like:

(\\s|.)*

Read about Regex here.

You can read a tutorial on String Patterns here.

Upvotes: 1

Related Questions