Java 将字符串拆分为句子的正则表达式
我需要拆分包含以下句子的字符串:Java 将字符串拆分为句子的正则表达式,java,regex,string,Java,Regex,String,我需要拆分包含以下句子的字符串: "this is a sentence. this is another. Rawlings, G. stated foo and bar." 进入 使用正则表达式 我找到的其他解决方案将第三句话分成了“Rawlings,G.”和“stated foo and bar。”这不是我想要的。通过嵌套的lookbehind 只需根据下面的正则表达式拆分输入字符串。下面的正则表达式将根据点后面的边界分割输入字符串,并检查前面的点字符。仅当dot的前一个字符不是大写字
"this is a sentence. this is another. Rawlings, G. stated foo and bar."
进入
使用正则表达式
我找到的其他解决方案将第三句话分成了
“Rawlings,G.”
和“stated foo and bar。”
这不是我想要的。通过嵌套的lookbehind
只需根据下面的正则表达式拆分输入字符串。下面的正则表达式将根据点后面的边界分割输入字符串,并检查前面的点字符。仅当dot的前一个字符不是大写字母时,它才会拆分
String s = "this is a sentence. this is another. Rawlings, G. stated foo and bar.";
String[] tok = s.split("(?<=(?<![A-Z])\\.)");
System.out.println(Arrays.toString(tok));
说明:
[this is a sentence., this is another., Rawlings, G. stated foo and bar.]
(?正则表达式通常不能解决此问题 你需要一个句子检测算法,有一个吗 使用起来非常简单:
处理很多棘手的案件String sentences[] = sentenceDetector.sentDetect(yourString);
- “小沃尔特·怀特有钱”
- “平克先生不给小费”
- 我试过这个
出局是import java.text.BreakIterator; import java.util.Locale; public class StringSplit { public static void main(String args[]) throws Exception { BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US); String source = "This is a sentence. This is another. Rawlings, G. stated foo and bar."; iterator.setText(source); int start = iterator.first(); for ( int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) { System.out.println(source.substring(start, end)); } } }
This is a sentence. This is another. Rawlings, G. stated foo and bar.
检查前一个字符是否不是大写字母check\。\s{2}vs\。原因是句子在句点后以两个空格结尾,但G.只有一个空格。因为Java 1。0@Holger您应该将此作为答案发布!您可以添加一行解释吗?这样会有帮助。我建议在
之后添加一个空格,即”(?在向您的项目添加第三方库依赖项之前,总是值得检查一下……这很公平,但您不能教breakIterator如何处理某些情况。
This is a sentence. This is another. Rawlings, G. stated foo and bar.