Nick
Nick

Reputation: 313

Check if String has specific repetitive special characters only

I have a string of format ^%^%^%^%. I need to check if the string has nothing other than repetitive patterns of ^%

For example

1. ^%^%^%^% > Valid

2. ^%^%aa^%^% > Invalid

3. ^%^%^%^%^%^% > Valid

4. ^%^%^^%^% > Invalid

5. %^%^%^%^% > Invalid

How do I do this in Java?

I tried :

String text = "^%^%^%^%^%";
if (Pattern.matches(("[\\^\\%]+"), text)==true) {
    System.out.println("Valid");
} else {
    System.out.println("Invalid");
}

However it gives me Valid for cases 4 and 5.

Upvotes: 4

Views: 116

Answers (4)

Roland Illig
Roland Illig

Reputation: 41686

You can simply do:

if (str.replace("^%", "").isEmpty()) {
    …
}

The replace method replaces the string as often as possible, therefore it fits exactly what you need.

It also matches the empty string, which, according to the specification, "contains nothing else than this pattern". In cases like these, you should always ask whether the empty string is meant as well.

Upvotes: 2

Michał Turczyn
Michał Turczyn

Reputation: 37460

Try this pattern ^(?:\^%)+$

Explanation:

^ - match beginning of the string

(?:...) - non-capturing group

\^% - match ^% literally

(?:\^%)+ - match ^% one or more times

$ - match end of the string

Demo

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163527

In your pattern you use a character class which matches only 1 of the listed characters and then repeats that 1+ times.

You could use that ^ to anchor the start of the string and end with $ to assert the end of the string.

Then repeat 1+ times matching \\^%

^(?:\\^%)+$

Regex demo

Upvotes: 3

Amol Gharpure
Amol Gharpure

Reputation: 304

String[] text = {"^%^%^%^%","^%^%aa^%^%","^%^%^%^%^%^%","^%^%^^%^%","%^%^%^%^%" };
for (String t: text) {
    if(Pattern.matches(("[\\^\\%]+[a-z]*[a-z]*[(\\^\\%)]+"), t)==true) {
            System.out.println("Valid");
    } else {
            System.out.println("Invalid");
    }

}

Upvotes: -1

Related Questions