-3

文字列:があり、数字を数字と同じ回数繰り返すa8に置き換えたいとします。どの正規表現文字列を使用しますか?[0-9].

例: 入力文字列

8

出力

........
4

3 に答える 3

4

正規表現のみを使用してこれを行うことはできないため、一致した文字列を、一致を引数として関数を呼び出した結果に置き換えることができる言語またはライブラリ機能に依存する必要があります。

ルビーの場合:

   "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;
}
于 2013-08-13T17:26:11.793 に答える
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);
.........
于 2013-08-13T17:34:11.703 に答える