Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# RegEx - get only first match in string

Tags:

c#

regex

I've got an input string that looks like this:

level=<device[195].level>&name=<device[195].name>

I want to create a RegEx that will parse out each of the <device> tags, for example, I'd expect two items to be matched from my input string: <device[195].level> and <device[195].name>.

So far I've had some luck with this pattern and code, but it always finds both of the device tags as a single match:

var pattern = "<device\\[[0-9]*\\]\\.\\S*>";
Regex rgx = new Regex(pattern);
var matches = rgx.Matches(httpData);

The result is that matches will contain a single result with the value <device[195].level>&name=<device[195].name>

I'm guessing there must be a way to 'terminate' the pattern, but I'm not sure what it is.

like image 631
bugfixr Avatar asked Jul 22 '14 21:07

bugfixr


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 the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.


1 Answers

Use non-greedy quantifiers:

<device\[\d+\]\.\S+?>

Also, use verbatim strings for escaping regexes, it makes them much more readable:

var pattern = @"<device\[\d+\]\.\S+?>";

As a side note, I guess in your case using \w instead of \S would be more in line with what you intended, but I left the \S because I can't know that.

like image 189
Lucas Trzesniewski Avatar answered Oct 17 '22 13:10

Lucas Trzesniewski