按标点保存拆分

时间:2019-03-31 18:11:05

标签: java regex

我需要安全地将Java字符串拆分为单词和标点符号。

我尝试过这段代码,但是有一个问题,就是它不能正确地分隔括号。

 this.socket = io.connect('http://localhost:9092',{ 
 reconnection: true,
 reconnectionDelay: 500,
 jsonp: false,
 reconnectionAttempts: Infinity,
 transports: ['websocket']});

this.socket.on('connect',function(e){
  console.log("on Connect");
})

this.socket.on('connect_error', (err) => {
  console.log(err)
});

实际结果是

String sentenceString = "Hello from the outside(outside).";
sentenceString.split("(?=,|\\.|!|\\?|\\(|\\))|\\s");

预期结果应为

["Hello", "from", "the", "outside", "", "(outside", ")", "."]

1 个答案:

答案 0 :(得分:2)

而不是split,您应该尝试匹配正则表达式以获得所需的输出。尝试在Java中使用此正则表达式,

[a-zA-Z]+|\\p{Punct}

此处[a-zA-Z]+部分匹配一个或多个字母,而\\p{Punct}部分匹配任何标点字符,如果您熟悉POSIX表示形式,则等效于[[:punct:]] 。尝试将类似解决方案应用于支持POSIX表示形式的语言/工具的人们可以使用[a-zA-Z]+|[[:punct:]]正则表达式。

Java代码

List<String> list = new ArrayList<String>();
String s = "Hello from the outside(outside).";
Pattern p = Pattern.compile("[a-zA-Z]+|\\p{Punct}");
Matcher m = p.matcher(s);
while (m.find()) {
    list.add(m.group());
}
System.out.println(list);

根据需要打印输出,

[Hello, from, the, outside, (, outside, ), .]

编辑:感谢Andreas的好建议。如果您不仅想包含英文字母,还想包含其他语言的字母,那么最好使用此正则表达式,

\\p{L}+|\\p{P}

因此,\\p{L}不仅将覆盖英语,而且还将覆盖以Unicode表示的任何其他语言的字母。

但是,请注意,这可能会增加性能代价,因为现在,它可能不仅试图匹配[a-z],而且还试图匹配其他Unicode字符。因此,需要进行一些折衷,因此请使用更适合您需求的解决方案。

再次感谢Andreas的宝贵建议。

相关问题