Hemant Menon
Hemant Menon

Reputation: 198

How do I change the following pattern to find all possible matches?

I have a Java pattern here

    String patternString = "(#)(.+?)([\\s,#.])";

I basically want to find all words beginning with a '#' in a given text string. The pattern matches all words except the last one if it is followed by an end line. I am using a hash map to store the values.

    int x = 0;

    HashMap<Integer, String> values = new HashMap<>();

    while(matcher.find()) {
        values.put(x++, matcher.group(2));
    }

I have tried putting a '$' symbol in the third to match the group but it doesn't seem to work. How do I tweak the pattern to match all words beginning with a '#' that includes the last word too?

Upvotes: 0

Views: 68

Answers (1)

KarelPeeters
KarelPeeters

Reputation: 1465

Unless I misunderstood your requirements, it can be much simpler. I'd suggest using the following pattern:

(#)([^\s]+)

It matches a # followed by as many non-white space characters as possible. You'll have to change you code to use group 1 instead of group 2, as my pattern doesn't have 3 groups.

Depending on your exact requirements you can also use \w instead of [^\s] to match any word character (equivalent to [a-zA-Z0-9_]).

Upvotes: 1

Related Questions