tags:

views:

615

answers:

4

I decided to use Regex, now I have two problems :)

Given the input string "hello world [2] [200] [%8] [%1c] [%d]",

What would be an approprite pattern to match the instances of "[%8]" "[%1c]" + "[%d]" ? (So a percentage sign, followed by any length alphanumeric, all enclosed in square brackets).

for the "[2]" and [200], I already use

Regex.Matches(input, "(\\[)[0-9]*?\\]");

Which works fine.

Any help would be appreicated.

+1  A: 

Try this:

Regex.Matches(input, "\\[%[0-9a-f]+\\]");

Or as a combined regular expression:

Regex.Matches(input, "\\[(\\d+|%[0-9a-f]+)\\]");
Gumbo
A: 

How about @"\[%[0-9a-f]*?\]"?

string input = "hello world [2] [200] [%8] [%1c] [%d]";
MatchCollection matches = Regex.Matches(input, @"\[%[0-9a-f]*?\]");
matches.Count // = 3
Samuel
+2  A: 
MatchCollection matches = null;
try {
    Regex regexObj = new Regex(@"\[[%\w]+\]");
    matches = regexObj.Matches(input);
    if (matches.Count > 0) {
     // Access individual matches using matches.Item[]
    } else {
     // Match attempt failed
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Lieven
Considering the contents of the sample string he posted, it would seem that [%xx] is a notation for a number in hex. Therefore, I don't thing matching any character is the right solution.
Samuel
@Samuel - that might be conveyed by his example but the OP explicitly said "followed by any length alphanumeric". BTW, if it only should be hex, perhaps it's better to make your solution case insensitive.
Lieven
No, not hex, sorry for the confusion.
Cheers, Lieven. That was perfect.
Lieven, yeah, not hex, but I realise that the solution I have now should be case insensitive anyway, so thanks for the reminder.
@ac2u - don't mention it.
Lieven
+1  A: 

The Regex needed to match this pattern of "[%anyLengthAlphaNumeric]" in a string is this "[(%\w+)]"

The leading "[" is escaped with the "\" then you are creating a grouping of characters with the (...). This grouping is defined as %\w+. The \w is a shortcut for all word characters including letters and digits no spaces. The + matches one or more instances of the previous symbol, character or group. Then the trailing "]" is escaped with a "\" and catches the closing bracket.

Here is a basic code example:

string input = @"hello world [2] [200] [%8] [%1c] [%d]";
Regex example = new Regex(@"\[(%\w+)\]");
MatchCollection matches = example.Matches(input);
Tinidian