0

I want to split a string into 2 strings,

my string looks like: HAMAN*3 whitespaces*409991

I want to have two strings the first with 'HAMAN' and the second should contain '409991'

PROBLEM: My second string has '09991' instead of '409991' after implementing this code:

        string str = "HAMAN   409991     ";
        string[] result = Regex.Split(str, @"\s4");
        foreach (var item in result)
        {
            MessageBox.Show(item.ToString());
        }

CURRENT SOLUTION with PROBLEM:

Split my original string when I find whitespace followed by the number 4. The character '4' is missing in the second string.

PREFERED SOLUTION:

To split when I find 3 whitespaces followed by the digit 4. And have '4' mentioned in my second string.

4

4 回答 4

2

Try this

string[] result = Regex.Split(str, @"\s{3,}(?=4)");

Here is the Demo

于 2013-11-15T10:52:56.073 回答
1

Positive lookahead is your friend:

Regex.Split(str, @"\s+(?=4)");
于 2013-11-15T10:53:58.750 回答
1

Or you could not use Regex:

var str = "HAMAN   409991     ";

var result = str.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

EXAMPLE


Alternative if you need it to start with SPACESPACESPACE4:

var str = new[] { 
    "HAMAN   409991     ",
    "HAMAN  409991",
    "HAMAN   509991"
};

foreach (var s in str)
{
    var result = s.Trim()
                  .Split(new[] {"   "}, StringSplitOptions.RemoveEmptyEntries)
                  .Select(a => a.Trim())
                  .ToList();

    if (result.Count != 2 || !result[1].StartsWith("4"))
        continue;

    Console.WriteLine("{0}, {1}", result[0], result[1]);
}
于 2013-11-15T10:54:52.533 回答
0

That's because you're splitting including the 4. If you want to split by three-consecutive-spaces then you should specify exactly that:

string[] result = Regex.Split(str, @"\s{3}");
于 2013-11-15T10:52:40.447 回答