1

I'm trying to use RegEx to split a string into several objects. Each record is separated by a :, and each field is separated by a ~.

So sample data would look like:

:1~Name1:2~Name2:3~Name3

The RegEx I have so far is

:(?<id>\d+)~(?<name>.+)

This however will only match the first record, when really I would expect 3. How do I get the RegEx to return all matches rather than just the first?

3 Answers 3

3

Your last .+ is greedy, so it gobbles up the Name1 as well as the rest of the string.

Try

:(?<id>\d+)~(?<name>[^:]+)

This means that the Name can't have a : in it (which is probably OK for your data), and makes sure the name doesn't grab into the next field.

(And also use the Regex.Matches method which grabs all matches, not just the first).

Sign up to request clarification or add additional context in comments.

Comments

1

Use:

var result = Regex.Matches(input, @":(?<id>\d+)~(?<name>[^:]+)").Cast<Match>()
    .Select(m => new 
    { 
        Id = m.Groups["id"].Value, 
        Name = m.Groups["name"].Value 
    });

Comments

1

you better use .split() method for strings.

String[] records = myString.split(':');
for(String rec : records)
{
    String[] fields = rec.split('~');
    //use fields
}

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.