6

I have a pipe delimited string of NAME|VALUE pairs looking something like this..

Name1|Value1|Name2|Value2|Name3|Value3

What I want to do is to replace every second instance of | with a new line so that I have something like this..

Name1|Value1
Name2|Value2
Name3|Value3

My issue isn't the new-line, as I know I can use \r\n for that, but rather the regex part that only replaces every second instance of |.

10

Find: ([^\|]*\|[^\|]*)\|
Replace to: \1\n

  • 1
    That doesn't work. – DavidPostill Aug 19 '15 at 8:56
  • 1
    I tried this, but this just adds a new line without actually splitting the string at the |'s – Pieter van Niekerk Aug 19 '15 at 8:56
  • I've corrected and tried, it works for me now. Sorry for the previous version. – Máté Juhász Aug 19 '15 at 9:00
  • @nixda: it was working for me also before your correction, | isn't a special character in that situation, it doesn't need to be escaped – Máté Juhász Aug 19 '15 at 9:04
  • In my Notepad version (6.6.9) they need to be escaped. Don't know what to tell. Its just not working without – nixda Aug 19 '15 at 9:06
3

I want to replace every second instance of | with a new line

  • Menu "Search" > "Replace" (or Ctrl + H)

  • Set "Find what" to (.*?\|.*?)[\|]

  • Set "Replace with" to \1\r\n

  • Enable "Regular expression"

  • Click "Replace All"

    enter image description here

Before:

Name1|Value1|Name2|Value2|Name3|Value3

After:

Name1|Value1
Name2|Value2
Name3|Value3

Notes:

  • The above assumes you are editing a text file with Windows EOLs, \r\n.

  • If you are using files with different EOLs you can convert them to Windows EOLs using Menu "Edit" > "EOL Conversion".

  • If you aren't working with Windows EOL, and you don't wish to convert them, use the following instead:

    • Use \n instead of \r\n for Unix/OS X EOLs

    • Use \r instead of \r\n for Mac OS (up to version 9) EOLs


Further reading

  • The regex provided is rather questionable: the first .*?, as a non-greedy match, will never match anything because there is nothing to its left to anchor it. It effectively becomes a no-op. – Bob Jan 3 '18 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.