1

Regex.Replace2桁ごとに文字列を実行する方法を考えていました。例: ユーザーが 111213 と入力した場合、11 を c に、12 を o に、13 を m に置き換えます。

明らかに、以前に各文字に値を割り当てましたが、2桁ごとに置換するように指示する正規表現について十分に知りません。

良い記事への助けやポインタをいただければ幸いです。

ラファエル・ルアレス。

4

3 に答える 3

4

正規表現をまったく使用しようとはしません。私が読んだように、2文字ごとに別の文字に置き換えたいだけです。このようなもの:

private static readonly Dictionary<string, string> Map
    = new Dictionary<string, string> {
    {"11", "c"},
    {"12", "o"},
    {"13", "m"}
};
public static string Rewrite(string input)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < input.Length; i += 2)
    {
        string value = input.Substring(i, 2);
        sb.Append(Map[value]);
    }
    return sb.ToString();
}
于 2012-07-29T19:24:57.320 に答える
2

入力文字列に数字のみが含まれている場合は、他の解決策が存在します。このコード スニペットは、2 桁の数字をすべて検出し、他の文字に関係なくそれらを置き換えます。他のソリューションに関係なく、個人的には、これは非常に簡単で理解しやすいと思います。

Dictionary<string, string> map = new Dictionary<string, string>();
map["11"] = "c";
map["12"] = "o";
map["13"] = "m";

string inputText = @"111213";

string outputText = Regex.Replace(inputText, @"\d\d", (MatchEvaluator)delegate(Match match)
{
    return map[match.Value];
});
于 2012-07-29T19:32:32.523 に答える
-1

編集

StringRegexメソッドを組み合わせて使用​​しました:

// you can add to list your replacement strings to this list 
var rep = new List<string> {"c", "o", "m"};
var inputString = "user types 111213";

// this replace first two numbers with 'c', second with 'o' and third with 'm'

foreach (string s in rep)
{
    Match match = Regex.Match(inputString, @"(\d{2})");
    if (match.Success)
        inputString = inputString.Remove(match.Index, 2).Insert(match.Index, s);
}
于 2012-07-29T19:17:42.903 に答える