0

i want a Regex expression to split a string based on \r characters not a carriage return or a new line.

Below is the sample string i have.

MSH|^~\&|1100|CB|CERASP|TESTSB8F|202008041554||ORU|1361|P|2.2\rPID|1|833944|21796920320|8276975

i want this to be split into

MSH|^~\&|1100|CB|CERASP|TESTSB8F|202008041554||ORU|1361|P|2.2
PID|1|833944|21796920320|8276975

currently i have something like this

StringUtils.split(testStr, "\\r");

but it is splitting into

MSH|^~
&|1100|CB|CERASP|TESTSB8F|202008041554||ORU|1361|P|2.2
PID|1|833944|21796920320|8276975
anubhava
  • 761,203
  • 64
  • 569
  • 643
suri
  • 41
  • 1
  • 2

3 Answers3

1

You can just use String#split:

final String str = "MSH|^~\\&|1100|CB|CERASP|TESTSB8F|202008041554||ORU|1361|P|2.2\\rPID|1|833944|21796920320|8276975";
        
final String[] substrs = str.split("\\\\r");
System.out.println(Arrays.toString(substrs));
// Outputs [MSH|^~\&|1100|CB|CERASP|TESTSB8F|202008041554||ORU|1361|P|2.2, PID|1|833944|21796920320|8276975]
enzo
  • 9,861
  • 3
  • 15
  • 38
1

You can use

import java.utl.regex.*;
//...
String[] results = text.split(Pattern.quote("\\r"));

The Pattern.quote allows using any plain text inside String.split that accepts a valid regular expression. Here, \ is a special char, and needs to be escaped for both Java string interpretation engine and the regex engine.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

The method being called matches any one of the contents in the delimiter string as a delimiter, not the entire sequence. Here is the code from SeparatorUtils that executes the delimiter (str is the input string being split) check:

if (separatorChars.indexOf(str.charAt(i)) >= 0) {

As @enzo mentioned, java.lang.String.split() will do the job - just make sure to quote the separator. Pattern.quote() can help.

ash
  • 4,867
  • 1
  • 23
  • 33