简体   繁体   中英

REGEX character Set substitution

I need a RegEx pattern that will allow me to substitute characters from one set to their corresponding characters in another set. for example: set [abcdefg], should be replaced with set [1234567]... So in a string of "bag", i want my replacement to be "217".

Regex regX = new Regex("([abcdefg])([1234567])");
string result = regX.Replace("bag", "$1$2");

My result is same as source. What should my replace pattern be?

Something like this will work much better than a Regex:

var fromCharacters = "abcdefghijklmnopqrstuvwxyz";
var toCharacters = "12345678901234567890123456";

var myString = "bag";

var sb = new StringBuilder(myString.Length);
for (int i = 0; i < myString.Length; ++i)
{
    sb.Append(toCharacters[fromCharacters.IndexOf(myString[i])]);
}

sb.ToString().Dump();

You could do something similar if you want, for example, 'j' to turn into '10', but you would need an array of Strings instead of being able to use a String as an array of chars.

I'm not sure how you would do this with a Regex, but I do know that you shouldn't.

string result = Regex.Replace("abcdefghiABCDEFGHI", "[a-zA-Z]", 
    m => (('a' <=  m.Value[0] && m.Value[0] <= 'z' 
               ? m.Value[0] - 'a' 
               : m.Value[0] - 'A') + 1).ToString());

Console.WriteLine(result);
// 123456789123456789

I used the MatchEvaluator delegate to replace each match with the corresponding value. See this for another example for it.

The problem with your pattern is that no one's expecting the numbers inside the input string, so it shouldn't be part of the pattern.

I'd use a Dictionary<char, char> for chars matching here:

var dict = "abcdefg"
    .Zip("1234567", (k, v) => new { k, v })
    .ToDictionary(i => i.k, i => i.v);
var result = string.Concat("bag".Select(c => dict[c]));

This will get you:

217

You havent mentioned a language, I'll tell how to do it in php. You can fixup according to your needs. In your case of replacement your parameters should be arrays.
$num = array("1", "2", "3", "4", "5", "6", "7");
$chr = array("a", "b", "c", "d", "e", "f", "g");

Then you can use either str_replace or preg_replace
$str = "This is a sample text";
echo str_replace($chr, $num, $str);

You can use regexp as first parameter as pattern but NOT for astring in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM