Quantcast
Viewing all articles
Browse latest Browse all 10

Replacing string within Regular Expressions Match

I have a trading partner who sends in invalid characters within a REF03 in an X12 850.  In the following example, my element separator is *, and the customer is sending in a * within the REF03.  I’m wanting to remove that invalid character before it hits the EDI pipeline component.

Example X12 850:

DTM*010*20110329~
PO1*10547090*1*EA*67.5**BP*PG7058SP—-~
PID*F****LDY FAITH INDIVIDUAL IRON~
REF*TC**HEREISMYINVALIDCHARACTER*~

I first captured all the TC Qualified Ref Segments into named groups (pre, text, and post) with the following Regular Expression.

@”(?<pre>REF\*TC\*\*)(?<text>.*?)(?<post>~)”

Using a method I am able to capture all the REF*TC segments, evaluate each one, and within each “text” group replace the errant * with “ “.  Note the use of the MatchEvaluator delegate within the Replace method.

private string myGoodString(string strBadString, string strSegmentTerminator)
        {
            string strRegex = @”(?<pre>REF\*TC\*\*)(?<text>.*?)(?<post>”+strSegmentTerminator+”)”;
            RegexOptions myRegexOptions = RegexOptions.None;
            Regex myRegex = new Regex(strRegex, myRegexOptions);

            string result = myRegex.Replace(strBadString, delegate(Match m)
            {
                return String.Join(String.Empty, new String[]{
                m.Groups[“pre”].Value,
                m.Groups[“text”].Value.Replace(“*”,” “),
                m.Groups[“post”].Value
            });

            });
            return result;
        }

Here is the resulting X12 850 snippet.

DTM*010*20110329~
PO1*10547090*1*EA*67.5**BP*PG7058SP—-~
PID*F****LDY FAITH INDIVIDUAL IRON~
REF*TC**HEREISMYINVALIDCHARACTER~


Viewing all articles
Browse latest Browse all 10

Trending Articles