简体   繁体   English

如何删除字符串中的特殊字符模式

[英]How to remove a special character pattern in a string

I have a string name s, 我有一个字符串名称s,

String s = "He can speak English and Sinhala.[1]He<ename> has edited 12 CSE Staff Research Publications.[1][2]"

I want to remove [1] and [1][2] from the string. 我想从字符串中删除[1][1][2] Note that we can have any number within the square brackets and any no of square brackets(like [number][number][number]... ). 请注意,我们可以在方括号内包含任何数字,也可以在方括号内没有任何数字(例如[number][number][number]... )。 I tried using this, 我试过用这个

String removedNoTag = s.replaceAll("[\\[0-9\\]]","");

Yes it removes all [number].. patterns. 是的,它删除了所有的[数字] ..模式。 But it also removes all numbers within the text (It removes 12 also). 但它也会删除文本中的所有数字 (也删除12 )。

Can anyone please tell me how to do this? 谁能告诉我该怎么做?

尝试以下操作: String removedNoTag = s.replaceAll("\\\\[\\\\d+\\\\]","");

You are escaping the wrong brackets in your regular expression. 您正在使用正则表达式转义错误的括号。 What you are looking for is: 您正在寻找的是:

String removedNoTag = s.replaceAll("\\[[0-9]+\\]","");

or 要么

String removedNoTag = s.replaceAll("\\[\\d+\\]","");

With \\d being the "short form of [0-9] . \\d[0-9]缩写。

Your outer brackets define a set of characters to remove. 括号定义了一组要删除的字符。 That set is defined as [ , ] and 0-9 . 该集合定义为[]0-9 So any combination of those is detected (for example [] , 2 , ] , [3] , [324] , ]1[[[ ). 因此,可以检测到它们的任何组合(例如[]2][3][324]]1[[[ )。

Instead try \\\\[\\\\d+\\\\] , which means the open bracket, one or more digits ( \\d ) and a closing bracket. 而是尝试\\\\[\\\\d+\\\\] ,这表示方括号,一个或多个数字( \\d )和方括号。

Because it removes any instance of a character that is either a number or a bracket. 因为它删除了数字或方括号字符的任何实例。

replace with : \\\\[[0-9]+\\\\] 替换为: \\\\[[0-9]+\\\\]

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

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