【问题标题】:Replace all the occurrence of {.?!"><',/\|@#$%^&*~`-_=+} with a word "myWord"将所有出现的 {.?!"><',/\|@#$%^&*~`-_=+} 替换为单词“myWord”
【发布时间】:2017-01-24 16:37:56
【问题描述】:

例如: 输入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");

【问题讨论】:

  • 你的意思是所有出现在大括号中的符号,或者大括号也是你要替换的符号?
  • 我也想去掉大括号...

标签: java replace pattern-matching replaceall


【解决方案1】:

你可以使用[^\\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);

【讨论】:

    【解决方案2】:

    你可以这样做:

    String str = "Hello there, How are you? Fine!! @xyz";
        str = str.replaceAll("[\\{\\.\\?!\"><',/\\\\\\|@#$%^&\\*~`\\-_=+\\}]", "myWord");
        System.out.println(str);
    

    输出:

    你好 theremyWord youmyWord FinemyWordmyWord myWordxyz 怎么样

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多