0

In C#, I'm receiving strings such as:

  • ABC123456DEF
  • 123456
  • ABC123456
  • 123456DEF

What I would like to do is split the numbers from the string so ideally the output for the above would be:

  • 'ABC', '123456', 'DEF
  • '123456'
  • 'ABC', '123456'
  • '123456', 'DEF'

Would someone please be able to advise the best way to handle this using Regex.Split?

Thank you.

Paul.

EDIT:

Being as I was marked down, I thought I better show what I have already. This only brings the alphanumeric's, not the numeric's:

string pattern = @"\d+";
string barcode = "ABC123456DEF";
string[] result = Regex.Split(barcode, pattern);
6
  • Which language are you running? Commented Nov 17, 2014 at 12:02
  • Sorry, C#. I'll amend the question. Commented Nov 17, 2014 at 12:02
  • Why don't you try matching instead of splitting? [A-Z]+|[0-9]+ Commented Nov 17, 2014 at 12:06
  • 1
    what effort have you made? Commented Nov 17, 2014 at 12:06
  • I would just match ([0-9]+)|([A-Z]+), no need for Regex.Split here Commented Nov 17, 2014 at 12:07

3 Answers 3

3

try this:

//Based on:

//.NET 4.5

//Program that uses Match, Regex: C#

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String subject = "ABC123456DEF\n123456\nABC123456\n123456DEF"
        Regex regex = new Regex(@"([a-zA-Z]+)|([0-9]+)");
        foreach (Match match in regex.Matches(subject))
        {
            MessageBox.Show(match.Value);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Regex.Split is exactly what you should use here:

using System.Text.RegularExpressions;
using System.Linq;

string pattern = @"(\d+)";
string barcode = "ABC123456DEF";
string[] result = Regex.Split(barcode, pattern).Where(s => !string.IsNullOrEmpty(s)).ToArray();

Comments

0

The Regexp.match approach in the other answer is likely better, however if you absolutely have to use Regexp.split the following pattern should work;

(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])

Comments

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.