1

Ive seen a few answers that are similar but none seem to go far enough. I need to split the string when the letters change to numbers and back. The trick is the pattern is variable meaning there can be any number of letter or number groupings.

For Example

AB1000 => AB 1000
ABC1500 => ABC 1500
DE160V1 => DE 160 V 1
FGG217H5IJ1 => FGG 217 H 5 IJ 1
Etc.
2
  • Please show us your best attempt so far, and tell us what went wrong (e.g. errors, unexpected results). Also, please explain why a regular expression is required. This job seems easy enough to do in a simple for loop (not that it would be the nicest solution, but it helps to understand the context). Commented Apr 9, 2015 at 21:20
  • The purpose for the regex is so I can put it in an extension method to be used against a linq query within a db context. I needed to be able to group by the first 2 segments of a model name. Commented Apr 10, 2015 at 1:13

2 Answers 2

4

If you want to split the string, one way would be lookarounds:

string[] results = Regex.Split("FGG217H5IJ1", @"(?<=\d)(?=\D)|(?<=\D)(?=\d)");
Console.WriteLine(String.Join(" ", results)); //=> "FGG 217 H 5 IJ 1"
Sign up to request clarification or add additional context in comments.

1 Comment

I was not familar with lookarounds. Thanks for the suggestion, it works great!
4

You can use a regex like this:

[A-Z]+|\d+

Working demo

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.