Ring
Ring

Reputation: 2309

My Regex Doesn't Work As I Expected

Heres my regex pattern:

[A-Z][a-z]?-?([A-Z][a-z]?)?

I want this regex to match the following:

A
Ab
Ef-G
Hi-Jk
F-Tk
F-D

I'm sending it "M-F" and it matches only on "F", I want it to match the entire string "M-F".

Heres my java code (but hopefully you shouldn't have to read it):

// Convert the daycode string into an array of daycodes
ArrayList<String> newDP = new ArrayList<String>();

Pattern regex = Pattern.compile("[A-Z][a-z]?-?([A-Z][a-z]?)?", Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(dayPattern);
while (regexMatcher.find())
{
  for (int i = 1; i <= regexMatcher.groupCount(); i++)
  {
    newDP.add(regexMatcher.group(i));
  }
}

Help me? Please and thank you.

Edit: I also need this to scale such that with an input of:

MTu-ThFSa

Returns an output of:

["M", "Tu-Th", "F", "Sa"]

Upvotes: 0

Views: 137

Answers (2)

porges
porges

Reputation: 30580

Your problem is that you are only adding groups 1 and upwards:

for (int i = 1; ...

With a regex match, group 0 is the overall match. Group 1 in your example is just the group in the second brackets: ([A-Z][a-z]?)?.

You should just change your loop to access group 0, which will be the whole match:

while (regexMatcher.find())
{
    newDP.add(regexMatcher.group(0));
}

For your edit in the original post:

Here is a fixed regex:

[A-Z][a-z]?(-[A-Z][a-z]?)?

The hyphen should only be allowed if there is a following letter.

Upvotes: 1

Supr
Supr

Reputation: 19022

Force it to match the whole string by using anchors: ^[A-Z][a-z]?-?([A-Z][a-z]?)?$

Though you should probably change the groupings a bit to really only match those. Something like:

^[A-Z]  ([a-z]  (-  ([A-Z]  ([a-z])?  )?  )?  )?$
        |-------------------------------------|
                |-------------------------|
                    |-----------------|
                            |-----|

Upvotes: 4

Related Questions