简体   繁体   English

如何使用REGEX在分度内的每个字符串后打印:|:模式

[英]How to use REGEX to print :|: pattern after each string within delimeters

Suppose i have a string "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]" like this. 假设我有这样的字符串"[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]" I am able to print [cat][dog][cow][monkey] from the above string. 我可以从上面的字符串中打印[cat][dog][cow][monkey] How can i print something like this = [cat]:|:[dog]:|:[cow]:|:[monkey] . 我如何打印类似= = [cat]:|:[dog]:|:[cow]:|:[monkey] please help. 请帮忙。

import java.util.regex.*;
public class RegexMain {

        static final String PATTERN = "\\[([^]]+)\\]|\"[^\"]*\"";
        static final Pattern CONTENT = Pattern.compile(PATTERN);

        public static void main(String[] args) {
            String test1 = "[cat] [] [dog] [cow] []  [] [monkey]";
            Matcher match = CONTENT.matcher(test1);
            while(match.find()) {
                if(match.group(1).length() != 0) {
                System.out.print(  match.group().trim());
            }

        }
    }
}

I am actually not sure what your string is exactly (you are using different ones in your explanation and code). 我实际上不确定您的字符串到底是什么(您在解释和代码中使用了不同的字符串)。 Anyways you can try this : 无论如何,您可以尝试以下方法:

public static void main(String[] args) {
    String s = "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]";
    System.out.println(s.replaceAll(":\\[\\]:\\|", ""));
}

O/P : O / P:

[cat]:|:[dog]:|:[cow]:|:[monkey]

怎么样

System.out.print(  match.group().trim() + ":|:");

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

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