如何在java中避免某些字符 [英] How to escape certain characters in java

查看:104
本文介绍了如何在java中避免某些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转义像 ^ [] + \ 标签和换行符不会是一个问题),而留下其他人如 *

I need to escape characters like ^, ., [, ], + and \ (tabs and newlines won't be an issue), while leaving others like * and ?.

EDIT =更具体来说,我有一个包含这些字符的字符串,我需要转义它们,以便它们不与正则表达式匹配。我需要为每个这些字符添加 \ ,但是单独进行这样的操作将需要7或8次扫描,我想在一次通过之中(IE:匹配的任何内容都以 \ 之前添加)

EDIT = More specifically, I have a string with these characters, and I need to escape them so that they are not matched by regular expressions. I need to prepend \ to each of these characters, but doing so individually would take 7 or 8 scans and I'd like to do it within just one pass (IE: anything that matches is prepended with \)

我该怎么做?

谢谢。

推荐答案

这个工作吗?

StringBuilder sb = new StringBuilder();
for (char c : myString.toCharArray())
{
    switch(c)
    {
        case '[':
        case ']':
        case '.':
        case '^':
        case '+':
        case '\\':
            sb.append('\\');
            // intended fall-through
        default:
            sb.append(c);
    }
}
String escaped = sb.toString();

这篇关于如何在java中避免某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆