1

I have a string variable being passed down to the method check() called 'letters' (Say). The string is therefore going to be dynamic.

The method requires checking if the words passed separately in an arraylist contain only the characters contain within 'letters'.

I have the following within my loop, with the word string changing each time as the loop iterates through the array.

word = wordArray.get(i);

if ((word.length() <= letters.length()) && (word.matches(letters))
{
    // Do something.
}

The string.matches() seems the way to go, however I'm having issues figuring out how I can use the letters string variable as an expression which the matches used, given the above code does not work.

My thoughts are that I may need to add certain expression characters, or perhaps escape the letters string? (I've played around with this though with no luck) Could anyone advise as to how I can ensure the word can only contain characters from the string variable 'letters'?

Thanks

1 Answer 1

1

You can do

Pattern p = Pattern.compile("[" + Pattern.quote(letters) + "]*");

and then later:

if (word.length() <= letters.length() && p.matcher(word).matches());
Sign up to request clarification or add additional context in comments.

1 Comment

@Error-404: You could also roll your own algorithm using a lookup or hash table. It's probably much faster to do it that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.