简体   繁体   English

匹配定界符管道之间的文本,将其删除并保持定界符完整

[英]Match the text between delimiter pipe and remove it and keep the delimiters intact

My issue is I have a String with a delimiter after every four characters. 我的问题是每四个字符后都有一个带分隔符的字符串。 I need to match a specific word to those four characters between the delimiters and remove it. 我需要将一个特定的单词与定界符之间的这四个字符进行匹配并将其删除。

Eg: String txt = "ABCD|BABA|SSRV|LKGD" 例如:字符串txt =“ ABCD | BABA | SSRV | LKGD”

Now check the String for BABA, DGHT, LKGD, ADKC and return the String minus these items 现在检查BABA,DGHT,LKGD,ADKC的字符串,并返回减去这些项目的字符串

Since we found a match for BABA and LKGD. 由于我们找到了BABA和LKGD的匹配项。 So the result should be the following 所以结果应该如下

Result: txt = "ABCD|SSRV" 结果:txt =“ ABCD | SSRV”

Any efficient way to do it? 有任何有效的方法吗?

You can use: 您可以使用:

String str = "ABCD|BABA|SSRV|LKGD";
String repl = str.replaceFirst("\\|BABA(?=\\||$)", "");
//=> ABCD|SSRV|LKGD

To remove both search strings together: 一起删除两个搜索字符串:

String str = "ABCD|BABA|SSRV|LKGD";
String repl = str.replaceAll("\\|(BABA|LKGD)(?=\\||$)", "");
//=> ABCD|SSRV

uses guava, but is quite readable. 使用番石榴,但可读性强。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.common.base.Joiner;

public class test {
    public static void main(String... args) {

        String txt = "ABCD|BABA|SSRV|LKGD";
        List<String> toBeRemoved = Arrays.asList(new String[] { "BABA", "DGHT","LKGD", "ADKC" });
        List<String> data = new ArrayList<>(Arrays.asList(txt.split("\\|")));
        data.removeAll(toBeRemoved);
        System.out.println(Joiner.on("|").join(data));

    }

}

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

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