I am trying to get the input from the user in a single Line with with [, ,] separators. Like this:
[Q,W,1] [R,T,3] [Y,U,9]
And then I will use these inputs in a function like this:
f.MyFunction('Q','W',1); // Third parameter will be taken as integer
f.MyFunction('R','T',3);
f.MyFunction('Y','U',9);
So, using Regex:
var funcArgRE = new Regex(@"\[(.),(.),(\d )\]", RegexOptions.Compiled);
foreach (Match match in funcArgRE.Matches(input))
{
var g = match.Groups;
f.MyFunction(g[1].Value[0], g[2].Value[0], Int32.Parse(g[3].Value));
}
But I also want to check the inputs if they have the same char combination Like
[Q,W,1] [U,Y,3] [Z,K,1] [Y,U,9]
if(theyHaveTheSame_Combination)
// do sth.
How can I do this inside the regex code piece?
CodePudding user response:
You can use
\[([A-Za-z]),([A-Za-z]),(\d )](?=.*\[(?:\1,\2|\2,\1),\d ])
Or, if you can really have anything in place of letters:
\[(.),(.),(\d )](?=.*\[(?:\1,\2|\2,\1),\d ])
See the regex demo.
Details:
\[(.),(.),(\d )]
- a[
char, any single char (Group 1), comma, any single char (Group 2), comma, one or more digtis (Group 3),]
char(?=.*\[(?:\1,\2|\2,\1),\d ])
- a positive lookahead that requires the following pattern to appear immediately to the right of the current location:.*
- any zero or more chars other than line break chars as many as possible\[
- a[
char(?:\1,\2|\2,\1)
- Group 1 value, comma, Group 2 value, or Group 2 value, comma, Group 1 value,\d ]
- comma, one or more digits,]
char.
CodePudding user response:
Regex can help you parse the input string, but to compare the different inputs to see if any are duplicates, you will need some other logic.
The structure of your data seems to be this:
class Command {
public char Letter1;
public char Letter2;
public int Number;
}
class CommandBatch {
public Command[] Commands;
}
You can use the regex you have to populate a CommandBatch
.
You can create a function to compare two Command
s, to see if they have matching letters.
bool AreMatching(Command c1, Command c2) {
return (c1.Letter1 == c2.Letter1 && c1.Letter2 == c2.Letter2)
|| (c1.Letter1 == c2.Letter2 && c1.Letter2 == c2.Letter1);
}
And then you can use that to make a function that checks a whole CommandBatch
.
bool AnyDuplicates(CommandBatch batch) {
var pairs = from c1 in batch.Commands
from c2 in batch.Commands
where c1 != c2
select (c1, c2);
return pairs.Any(tup => AreMatching(tup.Item1, tup.Item2));
}