KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm just getting to know regular expressions, but after doing quite a bit of reading (and learning quite a lot), I still have not been able to figure out a good solution to this problem. Let me be clear, I understand that this particular problem might be better solved not using regular expressions, but for the sake of brevity let me just say that I need to use regular expressions (trust me, I know there are better ways to solve this). Here's the problem. I'm given a big file, each line of which is exactly 4 characters long. This is a regex that defines "valid" lines: "/^[AB][CD][EF][GH]$/m" In english, each line has either A or B at position 0, either C or D at position 1, either E or F at position 2, and either G or H at position 3. I can assume that each line will be exactly 4 characters long. What I'm trying to do is given one of those lines, match all other lines that contain 2 or more common characters. The below example assumes the following: $line is always a valid format BigFileOfLines.txt contains only valid lines Example: // Matches all other lines in string that share 2 or more characters in common // with "$line" function findMatchingLines($line, $subject) { $regex = "magic regex I'm looking for here"; $matchingLines = array(); preg_match_all($regex, $subject, $matchingLines); return $matchingLines; } // Example Usage $fileContents = file_get_contents("BigFileOfLines.txt"); $matchingLines = findMatchingLines("ACFG", $fileContents); /* * Desired return value (Note: this is an example set, there * could be more or less than this) * * BCEG * ADFG * BCFG * BDFG */ One way I know that will work is to have a regex like the following (the following regex would only work for "ACFG": "/^(?:AC.{2}|.CF.|.{2}F
Tags (comma-separated)
Save Edits
Cancel