我是否总是需要在不是“文字”的字符串中转义元字符? [英] Do I always need to escape metacharacters in a string that is not a "literal"?

查看:113
本文介绍了我是否总是需要在不是“文字”的字符串中转义元字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在正则表达式处理期间,似乎拒绝包含字符 {} 的字符串。我可以理解这些是保留字符,如果我这样做,我需要逃避它们:

It seems that having a string that contains the characters { or } is rejected during regex processing. I can understand that these are reserved characters and I need to escape them so if I do:

string.replaceAll("\\" + pattern);

这是有效的,其中模式是任何字符串从 {开始。

This works, where pattern is any string starting with {.

问题:有没有办法避免此类问题已经包含此类metachars的字符串,以便自动处理?在我看来它应该与在字符串文字中添加双引号相比,接受字符串作为已经具有双引号的输入

Question: Is there a way to avoid such problems with strings that already contain such metachars so that it is handled automatically? Seems to me it should be the same as adding a double quote in a string literal vs accepting a string as input that already has the double quote

推荐答案

使用 Pattern.quote(String)


public static String quote(String s)

返回文字模式字符串表示指定的字符串

Returns a literal pattern String for the specified String.

此方法产生 String ,可用于创建一个模式,它将匹配字符串 s as如果它是一个文字模式。

This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

输入序列中的元字符或转义序列没有特殊含义。

Metacharacters or escape sequences in the input sequence will be given no special meaning.

参数:

     s - 要字面化的字符串

返回:

    文字字符串替换

自:

     1.5

Parameters:
    s - The string to be literalized
Returns:
    A literal string replacement
Since:
    1.5

这篇关于我是否总是需要在不是“文字”的字符串中转义元字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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