文字と文字のみの(\ba\b)
一致を表すために使用する場合、一致しません。の場合と同様に、になります。a
a
ab
b
(\bb\b)
string original = "a b c";
Regex[] expressions = new Regex[] {
// @ sign used to signify a literal string
new Regex(@"(\ba\b)"), // \b represents a word boundary, between a word and a space
new Regex(@"(\bb\b)"),
};
string[] replacements = new string[] {
"ab",
"c"
};
for(int i = 0; i < expressions.Length; i++)
original = expressions[i].Replace(original, replacements[i]);
編集1:質問が一致する文字の間にスペースを入れずに変更され、同じabcc
ものabc
が必要でした。正規表現がチェックされる順序を逆にしました。
Regex[] expressions = new Regex[] {
new Regex(@"b"), //replaced by c
new Regex(@"a"), //replaced by ab
};
string[] replacements = new string[] {
"c",
"ab",
};
編集2:一致する可変長を反映するように回答が変更されました。これは、チェックするパターンの順序に基づいて一致し、パターンをチェックしてから、新しい文字列に移動します
string original = "a bc";
Regex[] expressions = new Regex[] {
new Regex(@"a"), //replaced by ab
new Regex(@"b"), //replaced by c
};
string[] replacements = new string[] {
"ab",
"c",
};
string newString = string.Empty;
string workingString = string.Empty;
// Position of start point in string
int index = 0;
// Length to retrieve
int length = 1;
while(index < original.Length) {
// Retrieve a piece of the string
workingString = original.Substring(index, length);
// Whether the expression has been matched
bool found = false;
for(int i = 0; i < expressions.Length && !found; i++) {
if(expressions[i].Match(workingString).Success) {
// If expression matched, add the replacement value to the new string
newString += expressions[i].Replace(workingString, replacements[i]);
// Mark expression as found
found = true;
}
}
if(!found) {
// If not found, increase length (check for more than one character patterns)
length++;
// If the rest of the entire string doesn't match anything, move the character at **index** into the new string
if(length >= (original.Length - index)) {
newString += original.Substring(index, 1);
index++;
length = 1;
}
}
// If a match was found, start over at next position in string
else {
index += length;
length = 1;
}
}