我想知道如何生成一个正则表达式来检测单词中正则表达式的所有组合。例如:
"MAKE"
的匹配应返回 "M"、"MA"、"MAK"、"MAKE"、"AKE"、"AK"、"A"、"KE", "K", "E"
所以所有这些可能值的正则表达式是 [A-Za-z]+
问题是,如何从单个单词中检索所有可能的值:
Regex regex = new Regex( "[A-Za-z]+" );
foreach( Match m in regex.Matches( word ) )
{
for( int i = 0; i < m.Groups.Count; i++ )
Console.WriteLine( m.Groups[i].Value );
}
只检索我“MAKE”,但我想将所有匹配项分组到这个词中。
最佳答案
所以我试图用 Regex 制作一个字符串子串生成器的方法。 我有这个想法,但我不太清楚,但我终于找到了方法。还没有对它进行太多测试,但现在它可以工作并为可变大小的未知单词创建所有可能的子字符串(从左到右)。
它适用于 C# 正则表达式引擎。没有做过基准测试,也没有计算过复杂性(看起来像 O(N^2)?)。
我想用一种不同的方法来解决几个小时前在 Microsoft 面试中遇到的问题。重点是在对角线、水平和垂直方向(从左到右,从上到下)的 N 大小的 N 个单词(在下面的示例中,4 个大小为 4 的单词)的矩阵中找到所有可能的单词。
static void CheckWords( String[] words, HashSet<String> valid )
{
//Horizontal
foreach( var w in words )
FindWords( w, valid );
//Vertical
String word = "";
for( int i = 0; i < words.Length; i++ )
{
for( int j = 0; j < words[i].Length; j++ )
word += words[j][i];
FindWords( word, valid );
word = "";
}
//Diagonal
String word2 = "";
for( int i = 0, j = 0; i < words.Length; i++, j++ )
{
word += words[i][j];
word2 += words[i][words[i].Length - i - 1];
}
FindWords( word, valid );
FindWords( word2, valid );
}
static void FindWords( String word, HashSet<string> valid )
{
int len = word.Length;
//Generate all possible (left to right) substring for String with Length - a [ FOr example, for "MAKE" we can have possible values for "MAKE", "MAK", "MA", "M", "AKE", "KE", "K, "E", "A
for( int a = 0; a < len; a++ )
{
//Find all possible substring with this length { k = 1, k = 2, k = 3, ..., k = word.Length }
for( int k = 1; k <= word.Length; k++ )
{
Match match = new Regex(@"([A-Za-z]{" + k + "}){1}").Match(word);
//For all found groups, we just care for the first group wich contains the main unrepeated substrings
for( int i = 0; i < match.Groups.Count - 1; i++ )
for( int j = 0; j < match.Groups[i].Captures.Count; j++ ) //Check each permutation for each word with K length. You can Console.Write each value to check it's generated string
if( valid.Contains( match.Groups[i].Captures[j].Value ) )
Console.WriteLine( match.Groups[i].Captures[j].Value );
}
word = word.Substring( 1, word.Length - 1 );
}
}
所以给出这个输入:
HashSet<String> words = new HashSet<string>();
words.Add( "MAKE" );
words.Add( "MAD" );
words.Add( "END" );
words.Add( "MINE" );
String[] array = { "MAKE", "IEMY", "NIAH", "ENDN" };
CheckWords( array, words );
应该在字典中找到数组中的所有四个单词。
关于c# - 正则表达式在一个词中找到一组正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46839315/