2

How an I use regex to find anything between 2 ASCII codes? ASCII code STX (\u0002) and ETX (\u0003)

Example string "STX,T1,ETXSTX,1,1,1,1,1,1,ETXSTX,A,1,0,B,ERRETX"

Using Regex on the above my matches should be

,T1,
,1,1,1,1,1,1,
,A,1,0,B,ERR

Did a bit of googling and I tried the following pattern but it didn't find anything.

@"^\u0002.*\u0003$"

UPDATE: Thank you all, some great answers below and all seem to work!

3
  • 1
    Use @"\u0002.*?\u0003" Commented Jan 21, 2016 at 12:18
  • 2
    You can also try (?<=\x02).*?(?=\x03) if you don't like stx/etx in result. Commented Jan 21, 2016 at 12:27
  • Both answers work great. Commented Jan 21, 2016 at 12:32

3 Answers 3

4

You could use Regex.Split.

var input = (char)2 + ",T1," + (char)3 + (char)2 + ",1,1,1,1,1,1," + (char)3 + (char)2 + ",A,1,0,B,ERR" + (char)3;
var result = Regex.Split(input, "\u0002|\u0003").Where(r => !String.IsNullOrEmpty(r));
Sign up to request clarification or add additional context in comments.

1 Comment

Picked this as the answer as it was the first and worked. Cheers!
3

You may use a non-regex solution, too (based on Wyatt's answer):

var result = input.Split(new[] {'\u0002', '\u0003'}) // split with the known char delimiters
       .Where(p => !string.IsNullOrEmpty(p)) // Only take non-empty ones
       .ToList();

enter image description here

A Regex solution I suggested in comments:

var res = Regex.Matches(input, "(?s)\u0002(.*?)\u0003")
          .OfType<Match>()
          .Select(p => p.Groups[1].Value)
          .ToList();

Comments

3
            var s = "STX,T1,ETXSTX,1,1,1,1,1,1,ETXSTX,A,1,0,B,ERRETX";
            s = s.Replace("STX", "\u0002");
            s = s.Replace("ETX", "\u0003");

            var result1 = Regex.Split(s, @"[\u0002\u0003]").Where(a => a != String.Empty).ToList();
            result1.ForEach(a=>Console.WriteLine(a));

            Console.WriteLine("------------ OR WITHOUT REGEX ---------------");

            var result2 = s.Split(new char[] { '\u0002','\u0003' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            result2.ForEach(a => Console.WriteLine(a));

output:

,T1,
,1,1,1,1,1,1,
,A,1,0,B,ERR
------------ OR WITHOUT REGEX ---------------
,T1,
,1,1,1,1,1,1,
,A,1,0,B,ERR

1 Comment

Thanks for also including alternative to Regex

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.