remove substring in a string without using regex (cannot use replaceAll)

前端 未结 5 1802
深忆病人
深忆病人 2021-01-28 04:32

I need to remove some substrings in strings (in a large dataset). The substrings often contain special characters, like these: ., ^, /,... and replaceAll() would treat them as s

5条回答
  •  醉酒成梦
    2021-01-28 04:54

    You can match literally. For instance, if we want to match "<.]}^", we can do:

    Pattern pat=Pattern.compile("<.]}^", PATTERN.LITERAL");
    

    and use that pattern.

    You can also use backslashes to escape it. Note that the string literal itself needs backslashes, so escaping a single dot will take two backslashes, as follows:

    Pattern pat=Pattern.compile("\\.");
    

    First backslash is seen by compiler, and second backslash is taken as a backslash for the regex parser.

提交回复
热议问题