0

I have a string I need to split using a Regex. I could use the split methods in .NET but the string to return could be the first or second substrings. This regex will become a configurable setting in an application.

A typical string would be 9234567X123456-789

I've create the following regex

     [-09]([^X]*)X

to return the first substring. However, I lose the first digit, 234567 is returned.

Any ideas?

Thanks.

1
  • what data so you want..string separated by X or is it something else... Commented Oct 26, 2012 at 14:47

2 Answers 2

2

Yes, you lose the first digit because it's being taken by the [-09] part. It's not clear why you've got that at all. I suspect you just want:

([^X]*)X

In other words, "capture everything before the first X, and check that there really is an X."

Sample code:

using System;
using System.Text.RegularExpressions;

public class Test
{
    static void Main(string[] args)
    {
        Regex regex = new Regex("([^X]*)X");
        string input = "9234567X123456-789";
        Match match = regex.Match(input);
        // TODO: Check for success
        Console.WriteLine(match.Groups[1]); // 9234567
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm assuming that you want the string to start with either -, 0 or 9. If this is true the regex you need (and using regexes here is overkill unless you want to also perform a sort of validation) is

([-09]\d*)X

OR

([-09][^X]*)X

if you are allowing any kind of character (not only digits) in the part before the X

EDIT:

Might have understood what you are looking for reading your sample string:

9234567X123456-789

You need either the first or the second group and every group can have digits or hypen (-). You solve this by creating two groups:

([\d\-]+)X([\d\-]+)

then you can check Jon Skeet's answer to get the data. You could either use

match.Groups[1]); //to get 9234567

or

match.Groups[2]); //to get 123456-789

1 Comment

I was planning on performing some validation on the string as you guessed. The string must also start with a -, 0 or 9. I should have mentioned that in the question. Thanks!

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.