Reputation: 3
So I have a bonus task assigned and it asks to write a program which returns true if in a given string at least one character is repeated.
I am relatively new to regular expressions but to my knowledge this should work:
String input = "wool";
return input.matches(".*(.)/1+.*");
This should return true, because the '.*' at the beginning and the end express that there could be prefices or suffices. And the '(.)/1+' is a repeating pattern of any character.
As I said I'm relatively new to the regex stuff but I'm very interested in learning and understanding it.
Upvotes: 0
Views: 2328
Reputation: 198324
Almost perfect, just /
looks the wrong way around (should be \
).
Also, you don't need .*
for prefixes and suffixes - regexp will find a match anywhere in the string, so (.)\1
suffices. This is not an error, just an optimisation (although in other cases it might, and does, make a difference).
One more issue is that backslashes are special characters in Java strings, so when you write a regexp in Java, you need to double up on backslashes. This gives you:
return input.matches(".*(.)\\1.*");
EDIT: I forgot, you don't need +
because if something repeats 3 times, it also repeats 2 times, so you will find it just by searching for a two-character repetition. Again, not an error, just not needed here.
And Kita has a good point that your task is not well-defined, as it does not say whether you are looking for the repeating characters next to each other or anywhere in the string. My solution is for the adjacent characters; if you need the repetition anywhere, use his.
EDIT2 after comments: Forgot the semantics of .matches
. You guys are quite correct, edited appropriately.
Upvotes: 2
Reputation: 359
Alternative solution would be adding the elements to hashset. Then checking the length of the string and the hashset.
Upvotes: 0
Reputation: 2634
If the task "in a given string at least one character is repeated" includes the following pattern:
abcbd
(b
is repeated)then the regex pattern would be:
(.).*\1
This pattern assumes that other characters could be in between the repeating characters. Otherwise
(.)\1
will do.
Note that the task is to capture "at least one character is repeated", which means identifying a single occurrence is enough for the task, so \1
does not have to have +
quantifier.
The code:
return input.matches("(.).*\\1");
or
return input.matches("(.)\\1");
Upvotes: 0