gpt4 book ai didi

Java:正则表达式识别句子中的标点符号并删除它们

转载 作者:行者123 更新时间:2023-12-01 14:02:50 28 4
gpt4 key购买 nike

我有以下字符串:

String input = "Remove from em?ty sentence 1? Remove from sentence 2! But not from ip address 190.168.10.110!";

我想删除正确位置的标点符号。我的输出需要是:

String str = "Remove from em?ty sentence 1 Remove from sentence 2 But not from ip address 190.168.10.110";

我正在使用以下代码:

while (stream.hasNext()) { 
token = stream.next();
char[] tokenArray = token.toCharArray();
token = token.trim();

if(token.matches(".*?[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}[\\.\\?!]+")){
System.out.println("case2");
stream.previous();
int len = token.length()-1;
for(int i = token.length()-1; i>7; i--){
if(tokenArray[i]=='.'||tokenArray[i]=='?'||tokenArray[i]=='!'){
--len;
}
else
break;
}
stream.set(token.substring(0, len+1));
}
else if(token.matches(".*?\\b[a-zA-Z_0-9]+\\b[\\.\\?!]+")){
System.out.println("case1");
stream.previous();
str = token.replaceAll("[\\.\\?!]+", "");
stream.set(str);

System.out.println(stream.next());
}
}

“ token ”是从“输入”字符串发送的。您能否指出我在正则表达式或逻辑方面做错了什么?

标点符号在句子结束时被视为一个标点符号,不存在于 IP 地址中,也不存在于诸如 !trueemp?ty 之类的单词中(保留它们)独自的)。后面也可以跟一个空格或字符串结尾。

最佳答案

您可以使用此模式:

\\p{Punct}(?=\\s|$)

然后什么都不替换。

示例:

String subject = "Remove from em?ty sentence 1? Remove from sentence 2! But not from ip address 190.168.10.110!";
String regex = "\\p{Punct}(?=\\s|$)";
String result = subject.replaceAll(regex, "");
System.out.println(result);

关于Java:正则表达式识别句子中的标点符号并删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208809/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com