如何将转义字符添加到Java字符串?

时间:2013-08-27 17:03:17

标签: java string escaping

如果我有一个字符串变量:

String example = "Hello, I'm here";

我想在变量中的每个'" 前面添加一个转义字符(即实际上逃避字符),我该怎么做?

3 个答案:

答案 0 :(得分:16)

我不是在这里声称优雅,但我认为它做你想做的事(如果我弄错的话请纠正我):

public static void main(String[] args)
{
    String example = "Hello, I'm\" here";
    example = example.replaceAll("'", "\\\\'");
    example = example.replaceAll("\"", "\\\\\"");
    System.out.println(example);
}

输出

Hello, I\'m\" here

答案 1 :(得分:0)

尝试Apache Commons Text库-

library(tidyverse)
library(janitor)
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test

set.seed(42)
dat <- tibble(id=sample(LETTERS[1:3], size=100, replace=TRUE), date=sample(10, size=100, replace=TRUE))
dat
#> # A tibble: 100 x 2
#>    id     date
#>    <chr> <int>
#>  1 A         8
#>  2 A         7
#>  3 A         6
#>  4 A         1
#>  5 B         5
#>  6 B         9
#>  7 B         7
#>  8 A        10
#>  9 C        10
#> 10 C        10
#> # … with 90 more rows

dat %>% 
  get_dupes(id) %>% 
  group_by(id) %>% 
  arrange(desc(date)) %>% 
  slice(1)
#> # A tibble: 3 x 3
#> # Groups:   id [3]
#>   id    dupe_count  date
#>   <chr>      <int> <int>
#> 1 A             40    10
#> 2 B             39    10
#> 3 C             21    10

结果:

$ ( exit 516 ); echo $?
4

答案 2 :(得分:0)

对于那些来这里寻求更通用的转义解决方案的人,可以在Apache Commons Text库的基础上构建自己的转义符。看看StringEscapeUtils为例:

import org.apache.commons.text.translate.AggregateTranslator;
import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.LookupTranslator;

public class CustomEscaper {
    
    private static final CharSequenceTranslator ESCAPE_CUSTOM;
    
    static {
        final Map<CharSequence, CharSequence> escapeCustomMap = new HashMap<>();
                    
        escapeCustomMap.put("+" ,"\\+" ); 
        escapeCustomMap.put("-" ,"\\-" ); 
        ...
        escapeCustomMap.put("\\", "\\\\");
        ESCAPE_CUSTOM = new AggregateTranslator(new LookupTranslator(escapeCustomMap));
    }

    public static final String customEscape(final String input) {
        return ESCAPE_CUSTOM.translate(input);
    }
}