Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, August 1, 2017 10:38 AM
Hi
I'm trying to find the index of where the pattern was matched in a regex pattern, not a string.
The text entry is [21;23H
In this example I should return an index of 12 which is [0-9]+;[0-9]+(H|f)
var pattern = "\\[([1-2]J|J|(.*)0c|c|0n|3n|5n|6n|[0-9]+;[0-9]+R|R|7h|7l|[0-9]+;[0-9]+(H|f)|(H|f)|[0-9]+A|A|[0-9]+B|B|[0-9]+C|C|[0-9]+D|D|s|u|[0-9]+r|r|3g|g|1K|2K|K|1i|4i|5i|i|.;\".* \"p|(([0-2|4-5|7-8]|3[0-7]|4[0-7]).*m))";
string input = "[21;23H";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("Index:={0}", match.Index);
}
Is this possible?
All replies (8)
Tuesday, August 1, 2017 11:51 AM
why dont you separate your pattern in the individual expressions and match one by one until you find a match, then that would be the index you are looking for.
Wednesday, August 2, 2017 12:57 AM
The Index of a Match is the position in the input string where the match was found. Your input string is seven characters long. Why would you expect the index to be 12?
Wednesday, August 2, 2017 2:43 AM
Hi alketrazz,
According to your needs, as far as I know, you want to return the index of matched string, please check the following sample code:
Sample Code:
Regex rx = new Regex("as");
foreach (Match match in rx.Matches("saerasd2"))
{
int i = match.Index;
}
It return value 4.
Best Regards,
Eric Du
Wednesday, August 2, 2017 10:49 PM
var pattern = "\\[([1-2]J|J|(.*)0c|c|0n|3n|5n|6n|[0-9]+;[0-9]+R|R|7h|7l|[0-9]+;[0-9]+(H|f)|(H|f)|[0-9]+A|A|[0-9]+B|B|[0-9]+C|C|[0-9]+D|D|s|u|[0-9]+r|r|3g|g|1K|2K|K|1i|4i|5i|i|.;\".* \"p|(([0-2|4-5|7-8]|3[0-7]|4[0-7]).*m))";
string input = "[21;23H";
var patterns = patters.Split('|');
var i = 0;
var result = -1;
foreach(var p in patterns){
Regex rgx = new Regex(p);
Match match = rgx .Match(input);
if (match.Success)
result = i;
i++;
}
//result has the match position at this point
Saturday, August 5, 2017 2:47 PM
did this solved your issue?
Saturday, August 5, 2017 10:53 PM
did this solved your issue?
No
The question was about finding the index in the pattern that matches, not the position in the input string
Monday, August 7, 2017 3:40 AM
hi alketrazz:
Did this solved your issue?
Thursday, December 14, 2017 6:29 PM
Apologies for not replying, didn't realise my email account was actually disabled so didn't get any mails. I couldn't get this working
on the regex line kept getting not enough )'s
had to change the way it split the string. e.g. it was splitting on the pipes but it shouldn't split this** [0-9]+;[0-9]+(H|f)**
when it split on the pipe in the above it was missing a closing parenthesis
Once i created an array of each search string your solution worked.
Thanks