suri
suri

Reputation: 41

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

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

Upvotes: 0

Views: 118

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

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.

Upvotes: 1

ash
ash

Reputation: 5155

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.

Upvotes: 0

enzo
enzo

Reputation: 11496

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]

Upvotes: 1

Related Questions