e440. using the captured text of a group within a replacement pattern.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 13 行

TXT
13
字号
Just as it is possible to use the value of a group within the same pattern (see e439 Using the Captured Text of a Group within a Pattern), it is also possible to use a group value in the replacement pattern. Instead of a backslash, the form of the reference is $n where n is a group number starting from 0 (see e436 Capturing Text in a Group in a Regular Expression for more information on groups). 
    // Compile regular expression
    String patternStr = "\\((\\w+)\\)";
    String replaceStr = "<$1>";
    Pattern pattern = Pattern.compile(patternStr);
    
    // Replace all (\w+) with <$1>
    CharSequence inputStr = "a (b c) d (ef) g";
    Matcher matcher = pattern.matcher(inputStr);
    String output = matcher.replaceAll(replaceStr);
    // a (b c) d <ef> g

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?