gpt4 book ai didi

java - 正则表达式 (') 与 (,)

转载 作者:行者123 更新时间:2023-12-01 19:33:18 25 4
gpt4 key购买 nike

我试图从字符串中删除一些字符,但是我的正则表达式混淆了字符 (') 和 (,)。这是我的代码,但它不会删除 (,) 字符:

String str2 = "word,string,phrase";
System.out.println("----- " + str2.replaceAll("\\s+", " ").replaceAll("\\W+^'", " "));

如何指定正则表达式删除(,)而不删除(')。输出示例:

word string phrase

我的目标是删除除字符(')之外的所有非单词,例如单词(don't)中的字符(')预先感谢您。

最佳答案

How to specify to the regular expression to delete the (,) but not the (').

My goal is to delete all the non-word except the character (') like in the word (don't)

“删除 (,)”似乎是用空格替换。

“删除所有非单词”似乎意味着任何匹配 \W 的内容,除了:

  • ' 应保留
  • , 应替换为空格

首先,让我们查找所有不是 \w' 的字符:

[^\w',]

将它们替换为空(即删除它们)后,我们可以简单地将所有 , 替换为空格:

str2.replaceAll("[^\\w',]", "").replaceAll(",", " ")

这意味着原始字符串中的任何空格也将被删除,这与所描述的规则一致,因为空格是非单词。

关于java - 正则表达式 (') 与 (,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805460/

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