How to create regexReplace for a delimiter?

12

I have the following content:

123|321|1234\|56\|teste\||123

I would like to make a regex replace that would replace all | with line break and ignore | escaped with \ , so I would like to get the following return:

123
321
1234|56teste|
123

If someone has an alternative that is not regex , it works.

    
asked by anonymous 21.01.2014 / 12:08

2 answers

9

I found the answer in the stack overflow , but I'll translate here:

You can use this regex:

(?:\.|[^\|\]++)*

To get all content between pipes :

List<String> matchList = new ArrayList<String>();
try {
    Pattern regex = Pattern.compile("(?:\\.|[^\|\\]++)*");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group());
    } 

Explanation:

(?:        # Combina se...
 \.       # qualquer caracter escapado
|          # ou...
 [^\|\]++  # qualquer caracter exceto **|**
)*         # repita inúmeras vezes
    
21.01.2014 / 13:04
6

I would use a more straightforward translation than was stated: any | as long as it is not preceded by \ . This in regex is:

(?<!\)\|

With this, you can do this substitution on a single line:

"123|321|1234\|56\|teste\||123".replaceAll("(?<!\\)\|", "\n");
    
27.01.2014 / 19:03