Java如何在n个单词之后截断字符串?
package org.nhooo.example.regex;
public class GetNumberOfWordsFromString {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog.";
String one = truncateAfterWords(1, text);
System.out.println("1 = " + one);
String two = truncateAfterWords(2, text);
System.out.println("2 = " + two);
String four = truncateAfterWords(4, text);
System.out.println("4 = " + four);
String six = truncateAfterWords(6, text);
System.out.println("6 = " + six);
}
/**
* Truncate a string after n number of words.
*
* @param words number of words to truncate after.
* @param text the text.
* @return truncated text.
*/
public static String truncateAfterWords(int words, String text) {
String regex = String.format("^((?:\\W*\\w+){%s}).*$", words);
return text.replaceAll(regex, "$1");
}
}摘要的结果:
1 = The 2 = The quick 4 = The quick brown fox 6 = The quick brown fox jumps over
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短