Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex – Match everything except specified characters or split the string

I’m using this Regex [^,]+ that matches groups of non-commas but it needs to do this also for characters ; , \n and empty space.

I have this string 12f3,, 456;;;;\n\n227- , 999 from which I need to get all the substrings like 12f3 , 456, 227- and 999.

Is there a way of matching everything except some specified characters, or is best to use split in this situation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can match these substrings with [^\s;,]+ pattern. Splitting with [\s;,]+ is not recommended as there are often empty strings in the resulting array after splitting (due to either matches at the start/end of string, or consecutive matches).

See the regex demo.

In C#, use

var matches = Regex.Matches(text, @"[^\s;,]+")
    .Cast<Match>()
    .Select(x => x.Value)
    .ToList();

The [^\s;,]+ matches one or more (due to + quantifier) occurrences of any char other than ([^...] is a negated character class) a whitespace (\s), semi-colona dn a comma.

Non-regex approach

You can split your string with comma and semi-colon, remove empty entries and then trim the strings in the resulting array:

var text = "12f3,,   456;;;;\n\n227-   ,    999";
var res = text.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => x.Trim());
Console.WriteLine(string.Join("\n", res));

See the C# demo. Output:

12f3
456
227-
999
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading