0

我有一个看起来像这样的字符串: mynum(1234) and mynum( 123) and mynum ( 12345 ) and lastly mynum(#123)

我想#在括号中的数字前面插入一个,所以我有: 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 回答