用重复的字符替换数字

时间:2013-08-13 17:17:08

标签: regex

假设我有一个字符串:8,我想用[0-9]替换数字.,该数字将重复该数字的次数。我会使用什么正则表达式字符串?

例如:输入字符串

8

输出

........

3 个答案:

答案 0 :(得分:4)

您不能仅使用正则表达式来执行此操作,因此您必须依赖于语言或库功能,该功能允许使用匹配作为参数调用函数的结果替换匹配的字符串。

在Ruby中:

   "8".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "........"
 "812".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "..........."
"a1b2".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "a.b.."

在JavaScript中:

function replaceNumbersWithDots(str) {
  return (''+str).replace(/[0-9]/g, function(m) {
    var s='', num=parseInt(m, 10);
    for (i=0; i<num; i++) { s+= '.'; }
    return s;
  });
}
replaceNumbersWithDots('8');    // => "........"
replaceNumbersWithDots('812');  // => ".........."
replaceNumbersWithDots('a1b2'); // => "a.b.."

在Java中:

public static void main(String args[]) throws Exception {
  System.out.println(replaceNumbersWithDots("8"));    // => "........"
  System.out.println(replaceNumbersWithDots("812"));  // => "..........."
  System.out.println(replaceNumbersWithDots("a1b2")); // => "a.b.."
}
public static String replaceNumbersWithDots(String s) {
  Pattern pattern = Pattern.compile("[0-9]");
  Matcher matcher = pattern.matcher(s);
  StringBuffer buf = new StringBuffer();
  while (matcher.find()) {
    int x = Integer.parseInt(matcher.group());
    matcher.appendReplacement(buf, stringOfDots(x));
  }
  return buf.toString();
}
public static String stringOfDots(int x) {
  String s = "";
  for (int i=0; i<x; i++) { s += "."; }
  return s;
}

答案 1 :(得分:3)

单独使用标准正则表达式无法做到这一点。正如@ m.buettner指出的那样,您可以在某些语言中指定一个处理替换的函数。例如,使用Python

>>> import re
>>> s = '8'
>>> re.sub(r'\d', lambda m: '.'*int(m.group()), s)
'........'

但也许你甚至不需要正则表达式?由于你只是在寻找单字符匹配(即\d),你可以这样做:

  • 初始化某种字符串缓冲区以保存结果字符串
  • 循环输入字符串的字符
    • 如果字符是数字,则将其解析为整数,并将许多. s附加到缓冲区。
    • 否则,将角色本身附加到缓冲区。

以下是Java中的实现:

String s = "8";

StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
    if (Character.isDigit(c)) {
        int n = c - '0';

        for (int i = 0; i < n; i++)
            sb.append('.');
    } else {
        sb.append(c);
    }
}

System.out.println(sb);
........

答案 2 :(得分:2)

如果你没有提供lang,我做了一个在php中解决它的例子

$tr = array();
foreach(range(0, 9) as $nr)
{
  $tr[$nr] = str_repeat('.', $nr);
}

echo strtr("Hello 8", $tr);
// Gives: "Hello ........"
相关问题