我有一个小项目,我有一个输入句子,用户可以在其中指定变体:
The {small|big} car is {red|blue}
上面是一个例句,我想分成4个句子,像这样:
- 小车是红色的
- 大车是红色的
- 小车是蓝色的
- 大车是蓝色的
我似乎无法全神贯注地解决这个问题。也许有人可以帮助我。
编辑 这是我的初始代码
Regex regex = new Regex("{(.*?)}", RegexOptions.Singleline);
MatchCollection collection = regex.Matches(richTextBox1.Text);
string data = richTextBox1.Text;
//build amount of variations
foreach (Match match in collection)
{
string[] alternatives = match.Value.Split(new char[] { '|', '{', '}' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string alternative in alternatives)
{
//here i get problems
}
}
最佳答案
听起来您需要为此使用动态笛卡尔函数。埃里克·利珀特的 blog post为回应 Generating all Possible Combinations 而写.
首先,我们需要解析输入的字符串:
Regex ex = new Regex(@"(?<=\{)(?<words>\w+(\|\w+)*)(?=\})");
var sentence = "The {small|big} car is {red|blue}";
然后应该修改输入字符串以用于类似string.Format
的函数:
int matchCount = 0;
var pattern = ex.Replace(sentence, me =>
{
return (matchCount++).ToString();
});
// pattern now contains "The {0} car is {1}"
然后我们需要找到所有匹配项并应用 Eric 出色的 CartesianProduct
扩展方法:
var set = ex.Matches(sentence)
.Cast<Match>()
.Select(m =>
m.Groups["words"].Value
.Split('|')
).CartesianProduct();
foreach (var item in set)
{
Console.WriteLine(pattern, item.ToArray());
}
这将产生:
The small car is red The small car is blue The big car is red The big car is blue
and, finally, the CartesianProduct
method (taken from here):
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item}));
}
关于c# - 如何使用字符串操作生成一整套组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392500/