用单词 "myWord" 替换所有出现的 {.?!"><',/\|@#$%^&*~`-_=+}
Replace all the occurrence of {.?!"><',/\|@#$%^&*~`-_=+} with a word "myWord"
例如:
输入 String
是
Input = "Hello there, How are you? Fine!! @xyz"
输出为
Output = "Hello there myWord How are you myWord Fine myWord myWord myWord xyz"
我试过 Pattern
class 和 Matcher
class 但它只替换了一种模式和 str.replace(".","myWord");
你可以使用[^\w\s]
\s*[^\w\s]\s*
:\s*
表示一个或多个 space
[^\w\s]
: ^
不捕获 \w
和 \s
\w
意思是 a-zA-Z0-9_
\s
意思是space
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);
你可以这样做:
String str = "Hello there, How are you? Fine!! @xyz";
str = str.replaceAll("[\{\.\?!\"><',/\\\|@#$%^&\*~`\-_=+\}]", "myWord");
System.out.println(str);
输出:
Hello theremyWord How are youmyWord FinemyWordmyWord myWordxyz
例如:
输入 String
是
Input = "Hello there, How are you? Fine!! @xyz"
输出为
Output = "Hello there myWord How are you myWord Fine myWord myWord myWord xyz"
我试过 Pattern
class 和 Matcher
class 但它只替换了一种模式和 str.replace(".","myWord");
你可以使用[^\w\s]
\s*[^\w\s]\s*
:\s*
表示一个或多个 space
[^\w\s]
: ^
不捕获 \w
和 \s
\w
意思是 a-zA-Z0-9_
\s
意思是space
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);
你可以这样做:
String str = "Hello there, How are you? Fine!! @xyz";
str = str.replaceAll("[\{\.\?!\"><',/\\\|@#$%^&\*~`\-_=+\}]", "myWord");
System.out.println(str);
输出:
Hello theremyWord How are youmyWord FinemyWordmyWord myWordxyz