0

次のような文字列があります。 mynum(1234) and mynum( 123) and mynum ( 12345 ) and lastly mynum(#123)

#括弧内の数字の前に a を挿入したいので、次のようにします。mynum(#1234) and mynum( #123) and mynum ( #12345 ) and lastly mynum(#123)

これどうやってするの?数字の前に正規表現パターンマッチャーとreplaceAllチョークを使用すると、(

java.util.regex.PatternSyntaxException: 近くの閉じられていないグループ ...

例外。

4

1 に答える 1

4

試す:

String text = "mynum(1234) and mynum( 123) and foo(123) mynum ( 12345 ) and lastly mynum(#123)";
System.out.println(text.replaceAll("mynum\\s*\\((?!\\s*#)", "$0#"));

簡単な説明:

すべてのパターンを置き換えます:

mynum   // match 'mynum'
\s*     // match zero or more white space characters
\(      // match a '('
(?!     // start negative look ahead
  \s*   //   match zero or more white space characters
  #     //   match a '#'
)       // stop negative look ahead

部分文字列で:

$0#

$0 は、正規表現全体に一致するテキストを保持します。

于 2009-10-09T17:59:02.820 に答える