简体   繁体   English

replaceAll问题(我想删除所有出现的[*])

[英]Problems with replaceAll (i want to remove all ocurrences of [*])

i have a text with some words like [1], [2], [3] etc... 我有一个带有一些单词的文本,例如[1],[2],[3]等...

For example: houses both permanent[1] collections and temporary[2] exhibitions of contemporary art and photography.[6] 例如:既收藏当代艺术和摄影的永久作品[1],又收藏临时展览[2]。[6]

I want to remove these words, so the string must be like this: 我想删除这些单词,所以字符串必须是这样的:

For example: houses both permanent collections and temporary exhibitions of contemporary art and photography. 例如:既拥有当代艺术和摄影作品的永久收藏品又包括临时展览。

I tryed using: s = s.replaceAll("[.*]", ""); s = s.replaceAll("[.*]", "");使用: s = s.replaceAll("[.*]", ""); but it just remove the dots (.) from the text. 但它只是从文本中删除点(。)。

Wich is the correct way to achieve it? Wich是实现它的正确方法吗?

thanks 谢谢

It's because [ and ] are regex markers. 这是因为[]是正则表达式标记。 This should work: 这应该工作:

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

(assuming that you always have numbers within the [] ). (假设您始终在[]使用数字)。

If it could be any characters: 如果可以是任何字符:

s = s.replaceAll("\\[.*?\\]","");

(thanks @PeterLawrey). (感谢@PeterLawrey)。

Use: 采用:

s.replaceAll("\\[[^]]+\\]", "")

[ and ] are special in a regular expression and are the delimiters of a character class, you need to escape them. []在正则表达式中很特殊,并且是字符类的分隔符,您需要对其进行转义。 Your original regex was a character class looking either for a dot or a star. 您最初的正则表达式是寻找点或星号的字符类。

Step 1: get a better (safer) pattern. 步骤1:获得更好(更安全)的模式。 Your current one will probably remove most of your string, even if you do get it working as written. 您当前的字符串可能会删除您的大部分字符串,即使您确实按书面要求运行也是如此。 Aim for as specific as possible. 争取尽可能具体。 This one should do (only match brackets that have digits between them). 应该这样做(仅匹配括号之间有数字的括号)。

[\d+]

Step 2: escape special regex characters. 步骤2:转义特殊的正则表达式字符。 [] has a special meaning in regex syntax (character classes) so they need escaping. []在regex语法(字符类)中有特殊含义,因此需要转义。

\[\d+\]

Step 3: escape for string literal. 步骤3:对字符串文字进行转义。 \\ has a special meaning in string literals (escape character) so they also need escaping. \\在字符串文字(转义字符)中具有特殊含义,因此它们也需要转义。

"\\[\\d+\\]"

And now we should have some nicely working code. 现在我们应该有一些运行良好的代码。

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

Try: 尝试:

public class StringTest {



    public static void main(String args[]){
        String str = "houses both permanent[1] collections and temporary[2] exhibitions of contemporary art and photography.[6]";
        String patten = str.replaceAll("\\[[0-9]*]", "");

        System.out.println(patten);
    }
}

output: 输出:

houses both permanent collections and temporary exhibitions of contemporary art and photography. 既有当代艺术和摄影作品的永久收藏品又有临时展览。

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

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