How to set max limit for each word in the sentence using regex in java?

Member

by lizzie , in category: Third Party Scripts , a month ago

How to set max limit for each word in the sentence using regex in java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a month ago

@lizzie 

In order to set a maximum limit for each word in a sentence using regex in Java, you can use the following regular expression pattern:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
String sentence = "This is a sample sentence with some words";
int maxWordLength = 5;

String regex = "\b\w{1," + maxWordLength + "}\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sentence);

while (matcher.find()) {
    String word = matcher.group();
    System.out.println(word);
}


In the above code snippet, the regular expression pattern w{1,5} is used to match words that are between 1 and 5 characters long. You can adjust the maxWordLength variable to set your desired maximum limit for each word in the sentence.