例如:
输入String
是
Input = "Hello there, How are you? Fine!! @xyz"
和输出将是
Output = "Hello there myWord How are you myWord Fine myWord myWord myWord xyz"
我已经尝试过
Pattern
类和Matcher
类,但是它仅替换一种类型的模式和str.replace(".","myWord");
最佳答案
您可以使用[^\\w\\s]
\\s*[^\\w\\s]\\s*
:\\s*
表示一个或多个空格[^\\w\\s]
:^
不捕获\\w
和\\s
\\w
均值a-zA-Z0-9_
\\s
平均空间
String s="Hello there, How are you? Fine!! @xyz";
System.out.println(s.replaceAll("\\s*[^\\w\\s]\\s*", " myWord "));
输出:
Hello there myWord How are you myWord Fine myWord myWord myWord xyz
为了避免任何其他特殊字符,不应替换它们,然后将其添加到此
[]
例如\\s*[^\\w\\s:;\\[\\]]\\s*
中,如@ brso05所指出的那样演示版
const regex = /\s*[^\w\s\]\[;]\s*/g;
const str = `Hello there, How are you? Fine!! ; @xyz []`;
const subst = ` myWord `;
const result = str.replace(regex, subst);
console.log(result);