简体   繁体   中英

Replace piece of String based on Special Characters occurence using regex

I have a message String that separated by different special characters. For example,

MSG|027052^CMXV~MB^M^1^2^MD~GUY^M^1^2^MD|O|^1^2^STD||||027052^SCHROPP~GUY^M^^^MD

Now according to user inputs like,

-> 1(1).1 - Means in this string first occurrence of '|'(Occurrence of '~').Occurence of '^' -> O/P: M
-> 1(1) - Means in this string first occurrence of '|'(Occurrence of '~') -> O/P: GUY^M^1^2^MD
-> 1 - Means in this string first occurrence of '|' -> O/P: 027052^CMXV~MB^M^1^2^MD~GUY^M^1^2^MD

Now inputs can be one of three. Now I have to replace found piece of string (ex. {I: 1(1)} O: GUY^M^1^2^MD) with other string.

Following is piece of code that give only pipe separated regex.

String originalMsg = "MSG|027052^CMXV~MB^M^1^2^MD~GUY^M^1^2^MD|O|^1^2^STD||||027052^SCHROPP~GUY^M^^^MD";

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

O/P: MSG|ABC|O|^1^2^STD||||027052^SCHROPP~GUY^M^^^MD

EDIT:

String msg = originalMsg.replaceAll("^((?:[^|]*\\|){1}([^~]+.){2}))[^|]*", "$1ABC" );

O/P: MSG|027052^CMXVABC|O|^1^2^STD||||027052^SCHROPP~GUY^M^^^MD

It will only replace '|' separated string. I want one shot strategy that will replace according to user inputs.

Don't try to do this by hand and using regex'es. Use a HL7 parsing library. A good open source library for Java is HAPI . You can parse the HL7 message to an object, where You can access fields and change their values.

Also the syntax for accessing these values does not seem to conform to HL7 standards of addressing message fields. Might want to read up on HL7 standards also a bit. They should be freely available for download from HL7 organisation website

Definetely do remember - never write Your own HL7 parser, You will shoot Yourself in a foot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM