如何替换字符串中的括号 [英] How to replace brackets in strings

查看:366
本文介绍了如何替换字符串中的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含令牌的字符串列表。

令牌是:

I have a list of strings that contains tokens.
Token is:


{ARG:token_name}

{ARG:token_name}.

我还有令牌的哈希映射,其中key是令牌,值是我要用该标记代替的值。

I also have hash map of tokens, where key is the token and value is the value I want to substitute the token with.

当我使用replaceAll方法时,我会收到错误:

When I use "replaceAll" method I get error:


java。 util.regex.PatternSyntaxException:非法重复

java.util.regex.PatternSyntaxException: Illegal repetition

我的代码是这样的:

myStr.replaceAll(valueFromHashMap , "X"); 

,valueFromHashMap包含{和}。

and valueFromHashMap contains { and }.

我把这个hashmap作为一个参数。

I get this hashmap as a parameter.

推荐答案

正如其他人已经说过的, {模式(} 也)。
你必须逃避它,以避免任何混乱。

As others already said, { is a special character used in the pattern (} too). You have to escape it to avoid any confusion.

手动转移是危险的(你可能会省略一个,使你的模式完全错误)和乏味(如果你有很多特殊字符)。
处理这个的最好方法是使用 Pattern.quote()

Escaping those manually can be dangerous (you might omit one and make your pattern go completely wrong) and tedious (if you have a lot of special characters). The best way to deal with this is to use Pattern.quote()

相关问题

  • How to escape a square bracket for Pattern compilation
  • How to escape text for regular expression in Java

资源:

  • Oracle.com - JavaSE tutorial - Regular Expressions

这篇关于如何替换字符串中的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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