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
热门推荐
5 祝福语简短的微信
10 孙子生日祝福语简短精辟
11 校庆祝福语简短横幅
12 妈妈的祝福语简短优美
13 上班祝福语简短10字
14 牛年企业祝福语简短大气
15 长辈请客祝福语简短精辟
16 书法朋友祝福语简短精辟
17 财神祝福语简短网名
18 美丽祝福语老师文案简短