Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex get a match

Tags:

c#

regex

How can i get |ADT^A05| out of

"MSH|^~\&|PHTADT09|ABC|DADIST00|ABC|20120425152829|rcalini1|ADT^A05|20429208851634|P|2.1|560"

I have tried this but not working

"|([A-Z]{3})^([A-Z]{1})([0-9]{2})|"
like image 569
Yofi Avatar asked Dec 12 '12 21:12

Yofi


People also ask

How do I find regex matches?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

How do I match a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


3 Answers

I don't think you need Regex when there is a separator char like |

var adt = text.Split('|')[8];

See the definition of HL7 format

Each segment in a message is divided into composites, or fields, and the fields are separated by pipe characters ('|')

like image 79
L.B Avatar answered Oct 21 '22 17:10

L.B


You need to escape | and ^, as those are special characters in a Regex.

@"\|([A-Z]{3})\^([A-Z]{1})([0-9]{2})\|"

Or if you don't like verbatim literals:

"\\|([A-Z]{3})\\^([A-Z]{1})([0-9]{2})\\|"

Note that verbatim literals (using @ before the opening quote) make regexes SIGNIFICANTLY more readable (and more portable -- now you can just copy/paste that regex somewhere else). You should always use verbatim literals with regex strings unless you have a very good reason to do otherwise.

like image 20
ean5533 Avatar answered Oct 21 '22 15:10

ean5533


Put backslashes before certain characters: | and ^.

\|([A-Z]{3})\^([A-Z]{1})([0-9]{2})\|

Edit: My favorite site ever - http://regexpal.com/

like image 2
Nick Vaccaro Avatar answered Oct 21 '22 17:10

Nick Vaccaro