Erwin Ivanov
Erwin Ivanov

Reputation: 103

Matching ONE specific char then another then a minus ( - )

I'am trying to match the following regex: I have a String: F-F-W-F i need to write a regex, that checks if the first char is a W or F followed by an - . To check the String F-F-W-F.

This is what i came up with:

if(SBAKTIV.matches("[WF]{1}-[WF]{1}-[WF]{1}-[WF]{1}")) {
        SBAKTIVMessageForLog = "SBAKTIV: Okay";
        return true;

Upvotes: 0

Views: 44

Answers (1)

achAmháin
achAmháin

Reputation: 4266

As mentioned in the comments, your regex is good to go. Or perhaps can be shortened to ([WF]-)*[WF] or ([WF]-){3}[WF].

I'm only posting an answer to provide a non-regex based solution*, in case you end up wanting/needing one of those too:

for (int i = 0; i < word.length(); i++) {
    if (i % 2 == 0) {
        if (word.charAt(i) != 'F' && word.charAt(i) != 'W') {
            return false;
        }
    } else if (word.charAt(i) != '-') {
        return false;
    }
}
return true;

Demo

*This is based obviously on the length being ok, not null and so on

Upvotes: 1

Related Questions