2014-11-21 103 views
2

我想用正则表达式分割句子。JAVA按文字,标点符号和引号分割句子

一句话:

"Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I." 

当前正则表达式:

\\s+|(?<=[\\p{Punct}&&[^']])|(?=[\\p{Punct}&&[^']]) 

当前的结果:

{"Hallo", ",", "I'm", "a", "dog", ".", "The", "end", ".", "Someone", 
"said", ":", **""**, """ , "Earth", "is", "Earth", """, ".", "Is", "it", 
"good", "?", "I", "like", "it", "!", **"'He"**, "is", **"right'"**, 
"said", "I", "."} 

我有多余的""一次报价符号前,它不会分裂“从单词。

结果,我想:

{"Hallo", ",", "I'm", "a", "dog", ".", "The", "end", ".", "Someone", 
"said", ":", """ , "Earth", "is", "Earth", """, ".", "Is", "it", 
"good", "?", "I", "like", "it", "!", "'" , "He", "is", "right", "'", 
"said", "I", "."} 

编辑: 对不起!更多的代码,然后:

String toTest = "Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I."; 
String [] words = toTest.split("\\s+|(?<=[\\p{Punct}&&[^']])|(?=[\\p{Punct}&&[^']])"); 

,并产生单词列表: “ ”

话= { “你好”,“”, “我”, “一”, “狗”, “The”,“end”,“。”,“Someone”, “said”,“:”,“”“”,“”,“Earth”,“is”,“Earth” “”,“Is”,“it”, “好”,“?”,“我”,“like”,“它”,“!”,“'他”,“is”,“ right'“, ”said“,”I“,”。“}

+0

我在您的问题中看不到任何Java代码。 – 2014-11-21 13:04:29

+0

@LutzHorn正则表达式是一个Java代码。 – RealSkeptic 2014-11-21 13:05:46

+0

@RealSkeptic为什么不是Perl,Python或Ruby? – 2014-11-21 13:10:21

回答

4

你可以试试:

\\s+|(?<=[\\p{Punct}&&[^']])(?!\\s)|(?=[\\p{Punct}&&[^']])(?<!\\s)|(?<=[\\s\\p{Punct}]['])(?!\\s)|(?=['][\\s\\p{Punct}])(?<!\\s) 

said: \"Earth的问题是,你之前分裂和空间后,所以我加了负前瞻和负向后看的部件拆分围绕标点符号。

我还添加了两种情况,用于拆分单引号,前提是后跟空格或标点符号。

但是,正如@RealSkeptic在他的评论中写道,这不会照顾

一个单引号,它表示possesion像海豚鼻子

,您可能需要写一个真实解析器。

0

你可以尝试从你的话中分离的特殊字符:

yoursentence.replaceAll("([^\\w ])", " $1 ").split(" +"); 

这打乱了空间,但我猜你不需要关心有多少人在你的句子彼此相邻。此外,“位”比你更简单:d

可复制代码尝试:

public static void main(String[] args) { 
    String s = "Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I."; 
    String replaceAll = s.replaceAll("([^\\w ])", " $1 "); 
    List<String> asList = Arrays.asList(replaceAll.split(" +")); 

    for (String string : asList) { 
     System.out.println(string); 
    } 
} 
0

虽然有可能有一个正则表达式来解决这个问题,我的做法是把工作分成几个每一步都在做一件事。

因此,我建议你创建一个接口:

return Arrays.asList (input.get (0).split ("\\s+")); 

public interface IProcess { 
    List<String> process (List<String> input); 
} 

现在你可以用一个包含整个句子作为第一个元素,并返回用空格分开单词列表中开始

下一步是为每种特殊字符编写处理器并链接它们。例如,您可以在每个单词的末尾剥离.,!?以清理后续步骤的输入。

这样,每当发现错误并轻松缩小链中需要改进的部分时,您可以轻松地为每个处理器编写单元测试。

相关问题