简体   繁体   English

如何替换字符串中的括号

[英]How to replace brackets in strings

I have a list of strings that contains tokens. 我有一个包含令牌的字符串列表。
Token is: 令牌是:

{ARG:token_name}. {ARG:TOKEN_NAME}。

I also have hash map of tokens, where key is the token and value is the value I want to substitute the token with. 我还有令牌的哈希映射,其中key是令牌,value是我想用令牌代替的值。

When I use "replaceAll" method I get error: 当我使用“replaceAll”方法时,我收到错误:

java.util.regex.PatternSyntaxException: Illegal repetition java.util.regex.PatternSyntaxException:非法重复

My code is something like this: 我的代码是这样的:

myStr.replaceAll(valueFromHashMap , "X"); 

and valueFromHashMap contains { and }. 和valueFromHashMap包含{和}。

I get this hashmap as a parameter. 我把这个hashmap作为参数。

String.replaceAll() works on regexps. String.replaceAll()适用于String.replaceAll() {n,m} is usually repetition in regexps. {n,m}通常在regexp中重复。

Try to use \\\\{ and \\\\} if you want to match literal brackets. 如果要匹配文字括号,请尝试使用\\\\{\\\\}

So replacing all opening brackets by X works that way: 因此,用X替换所有左括号都是这样的:

myString.replaceAll("\\{", "X");

See here to read about regular expressions (regexps) and why { and } are special characters that have to be escaped when using regexps. 请参阅此处以了解正则表达式(regexps)以及为什么{}是使用regexp时必须转义的特殊字符。

As others already said, { is a special character used in the pattern ( } too). 正如其他人已经说过的那样, {是模式中使用的特殊字符( } )。 You have to escape it to avoid any confusion. 你必须逃避它以避免任何混淆。

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() 处理这个的最好方法是使用Pattern.quote()


Related issues: 相关问题:

Resources: 资源:

replaceAll() takes a regular expression as a parameter, and { is a special character in regular expressions. replaceAll()将正则表达式作为参数, {是正则表达式中的特殊字符。 In order for the regex to treat it as a regular character, it must be escaped by a \\ , which must be escaped again by another \\ in order for Java to accept it. 为了让正则表达式将其视为常规字符,它必须由\\来转义,必须由另一个\\再次转义,以便Java接受它。 So you must use \\\\{ . 所以你必须使用\\\\{

You can remove the curly brackets with .replaceAll() in a line with square brackets 您可以使用带方括号的行中的.replaceAll()删除大括号

String newString = originalString.replaceAll("[{}]", "X")

eg: newString = "ARG:token_name" 例如:newString =“ARG:token_name”

if you want to further separate newString to key and value, you can use .split() 如果你想进一步将newString分隔为键和值,你可以使用.split()

String[] arrayString = newString.split(":")

With arrayString, you can use it for your HashMap with .put() , arrayString[0] and arrayString[1] 使用arrayString,您可以将它用于带有.put()arrayString[0]arrayString[1] HashMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM