0

MSH|^~\&|RAD|MCH|SOARCLIN|MCH|201309281506||ORU^R01|RMS|P|2.4 PID|0001|_MISSING_|059805^a~059805^a~059805^a||RENNER^KATHRYN^

In a string like the above I need to replace the string on basis of | (pipe sign) count.

e.g. :

MSH line want to replace after 3rth position of (|) pipe sign "MCH" with "ABC"

input : MSH|^~\&|RAD|MCH|SOARCLIN|MCH|201309281506||ORU^R01|RMS|P|2.4

output : MSH|^~\&|RAD|MCH|SOARCLIN|ABC|201309281506||ORU^R01|RMS|P|2.4

2
  • 2
    We disagree where the 3rd pipe sign is. Commented Jan 29, 2015 at 14:28
  • that is example i given. position will be any number. Commented Jan 30, 2015 at 4:41

1 Answer 1

1
String repSection( String del, int count, String rep ){
    String[] toks = theString.split( Pattern.quote( del ) );
    toks[count] = rep;
    theString = String.join( del, toks );
}

Call:

String result = repSection( "|", 3, "ABC" );

It depends on counting alone; it doesn't matter what is there between the 3rd and 4th pipe char.

I prefer this to some fancy and difficult to maintain regex.

s = s.replaceAll( "^((?:[^|]*\\|){3})[^|]*", "$1|ABC" );

Again, this doesn't care what is between 3rd and 4th pipe symbol.

Sign up to request clarification or add additional context in comments.

2 Comments

hello @laune : is this possible to replace that pipe seperated content have also some inner seperated content. for example: PV1|027052^SCHROPP~GUY^M^1^2^MD|O|^1^2^MCH||||027052^SCHROPP~GUY^M^^^MD so now first occurrence of pipe and inside that content is 027052^SCHROPP~GUY^M^1^2^MD now first occurrence of ~ separated and content is this: GUY^M^1^2^MD inside that ~ separated i have another separated ^ separate and need to replace at occurrence of ^ at position 2 : Eg: 1 with K:
In this situation I would use the split/join approach with a recursive version of repSection and with modified arguments: repSection( String[] dels, int[]counts, String rep ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.