Ava String Split by "|"

64    Asked by jimmie_5779 in Java , Asked on Jul 27, 2025

In Java, splitting a string by the pipe symbol | can be tricky because it's a special character in regular expressions. Learn how to properly escape and use it with the split() method to break your string into parts.

Answered by Nakagawa Harada

To split a string by the | character in Java, you need to use the String.split() method. However, since the pipe (|) is a special character in regular expressions (it represents logical OR), you must escape it properly to use it as a literal character.

Here's how you can do it:

String text = "Java|Python|JavaScript";
String[] languages = text.split("\|"); // Note the double backslash
for (String lang : languages) {
    System.out.println(lang);
}

Key Points:

  • | is a special character in regex, so it must be escaped using \|.
  • In Java strings, \ is required because a single backslash is also an escape character in strings. So to get | in regex, you write \| in Java.
  • If you forget to escape it, you'll likely get unexpected results or runtime errors.

Things to Keep in Mind:

  • If you want to split by other regex special characters (like ., *, +, etc.), you also need to escape them.
  • Always test your splitting logic to ensure it behaves as expected.

Example Output:

Java  
Python
JavaScript

This method is commonly used in file parsing, processing user inputs, or handling data that comes in delimited formats. So remembering to escape regex characters in Java string operations is a helpful habit to build.



Your Answer

Interviews

Parent Categories