Search code examples
javaregexstringlimitstring-length

How to set max limit for each word in the sentence using Regex in JAVA


I want to throw an error when the word exceeds max length, but not the whole sentence length.

Example

if I am setting max length as 10, the sentence is "Hello stackOverflow" this should throw error since stackoverflow length more than 10 if I give as "Hello stack Overflow" Should be passed since none of the word is not exceeding max length 10. This should be achieved using Regex in Java


Solution

  • The following code snippet does what you request using the sample string in your question.

    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\w{11,}");
    java.util.regex.Matcher matcher = pattern.matcher("Hello stackOverflow");
    if (matcher.find()) {
        throw new Exception("Word too long.");
    }
    

    The regular expression searches for a series of at least eleven word characters and throws an exception if a match is found.