Mutaaf Aziz
Mutaaf Aziz

Reputation: 29

find pattern in string

Find the pattern “[Number1, Number2]” in any given string and get the integer (32bit) values for Number1 and Number2:

Example Input: “Foo Bar [45,66] Bash”

Example Result: Number1 = 45 Number2 = 66

I have this example in my deitel book and I can't seem to get the Regex Exp. syntax correct. Can anyone help me out?

Upvotes: 0

Views: 2660

Answers (2)

Christopher W. Szabo
Christopher W. Szabo

Reputation: 221

Regular expressions... they're so helpful now. Before the standard however, programmers didn't have the luxury of asking for community support on StackOverflow. In fact... many programmers encountered "stack overflows" while trying to perform a simple string search back in the day.

If you want to find a string with in a string and you don't have the ability to use regular expressions you have to search through the string for the expression in a very specific way. A string is a null terminated array of characters. That construct is implemented with the string class, but under the hood it's a character array with a null value in the final position.

Assume you had the following string:

string arrayOfCharactersToSearch = "This is the null terminated array of characters to search.";

Now assume you wanted to search for "array" with in that string. You would have to examine "chunks" of the characters in the string. But you couldn't do that by just moving one character at a time and then looking for "array" because it would be inefficient. You also can't do it by looking at chunks that are the same length as "array" because it might miss a combination of characters.

The solution is to advance each "chunk" by the length of the search criteria, in this case "array", divided by two, plus one:

    *chunk = ( string length / 2 ) + 1*

Fortunately, we have regular expressions now and all that BS is done for us under the hood, but it's still important to understand how it works... right??

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50235

This should work for your exact case of [number,number]:

var match = Regex.Match(input, @"\[(\d+),(\d+)\]");

var first = match.Groups[1].Value;
var second = match.Groups[2].Value;

var result = string.Format("Number1={0} Number2={1}", first, second);

Tested a myregextester.com.

Upvotes: 4

Related Questions