Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Split - everything inside square brackets

Tags:

c#

regex

split

I'm currently trying to split a string in C# (latest .NET and Visual Studio 2008), in order to retrieve everything that's inside square brackets and discard the remaining text.

E.g.: "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]"

In this case, I'm interested in getting "HSA:3269" and "PATH:hsa04080(3269)" into an array of strings.

How can this be achieved?

like image 423
João Pereira Avatar asked Apr 11 '09 19:04

João Pereira


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C full form?

Full form of C is “COMPILE”.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

Split won't help you here; you need to use regular expressions:

// using System.Text.RegularExpressions; // pattern = any number of arbitrary characters between square brackets. var pattern = @"\[(.*?)\]"; var query = "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]"; var matches = Regex.Matches(query, pattern);  foreach (Match m in matches) {     Console.WriteLine(m.Groups[1]); } 

Yields your results.

like image 79
Konrad Rudolph Avatar answered Oct 13 '22 06:10

Konrad Rudolph