How to create regexReplace for a delimiter?

Asked

Viewed 372 times

12

I have the following content:

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

I’d like to make a regex replace to replace all | by line break and ignore the | escaped with \, this way I would like to get the following feedback:

123
321
1234|56teste|
123

If anyone has an alternative other than regex also serves.

  • 1

    @leogaldioli On the META website we have a summary explanation how to apply color highlighting to code!

2 answers

9


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

This regex can be used:

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

To pick up all the content between the 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
  • 2

    Cool. I edited the question and put the code tags. See this page to learn how to put. It’s not hard.

6

I would use a more direct translation than was stated: any | provided that it is not preceded by \. That, in regex, is:

(?<!\\)\|

With this, you can make this substitution in a single line:

"123|321|1234\\|56\\|teste\\||123".replaceAll("(?<!\\\\)\\|", "\n");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.