11684
11684

Reputation: 7517

Matching text either side of a colon

I am trying to learn the basics of regular expressions (in Java) and imagined some sample scenarios to practice, and – as you might have expected – the last (and thus for me hardest) isn't working. Here it is:

<[a-zA-Z]>:[a-zA-Z]

What I want it to do is to recognize <SOME TEXT>:SOME MORE TEXT. With input like: <foo>:bar, it isn't working.

What am I doing wrong?

Upvotes: 1

Views: 219

Answers (2)

Michael Besteck
Michael Besteck

Reputation: 2423

If you want to also catch "SOME TEXT" literally, you need to catch white space too.

    String teststring = "<SOME TEXT>:SOME MORE TEXT";
    String regex = "<[\\sa-zA-Z]+>:[\\sa-zA-Z]+";
    Matcher m = Pattern.compile(regex).matcher(teststring);
    while (m.find())
    {
        System.out.println(teststring.substring(m.start(), m.end()));
    }

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171914

You're only matching one character. To match multiple, you need to add '+':

<[a-zA-Z]+>:[a-zA-Z]+

If the text is optional, you can also specify '*', which means "zero or more". '+' means "1 or more"

Upvotes: 3

Related Questions