• 正则表达式使用过程中的一个问题

    普通类
    • 支持
    • 批判
    • 提问
    • 解释
    • 补充
    • 删除
    • 问题描述

    在对一个字符串进行正则匹配,然后替换匹配项的时候,在调用Matcher的appendReplacement()方法的时候,发现报IllegalArgumentException错误。

    这个问题随着字符串的不同,有时候出现,有时候不出现。

    • 问题分析

    根据问题的描述,可以比较肯定的是船体的字符串的内容对其产生了影响。具体怎么产生影响的,却不是很清楚。

    随后想到直接查看JDK的源码,发现在Matcher的appendReplacement()方法中有这么一段。

     

    根据这段源码猜测,可能是在appendReplacement()方法的第二个参数中,可以利用$符号对匹配的组别进行引用。

    再查JDK的API,发现:

    The replacement string may contain references to subsequences captured during the previous match: Each occurrence of$g will be replaced by the result of evaluating group(g). The first number after the $ is always treated as part of the group reference. Subsequent numbers are incorporated into g if they would form a legal group reference. Only the numerals '0' through '9' are considered as potential components of the group reference. If the second group matched the string "foo", for example, then passing the replacement string "$2bar" would cause "foobar" to be appended to the string buffer. A dollar sign ($) may be included as a literal in the replacement string by preceding it with a backslash (\$).

    大概的意思就是在appendReplacement()方法的第二个参数中可用$符号可以对组别进行引用,和前面分析的基本一致。

    • 问题解决

    有了上面的分析和API说明,应该很好解决问题了,在进行字符串匹配之前,先进行字符的替换:

    str = str.replace("\$", "\\\$");

    这样就解决了这个问题。

    • 总结

    通过这个问题,发现了自己对于JDK的API还是不够熟练,因为API中已经明确说明$符号要进行转义。

    另外,这种解决问题的思路还是可以借鉴的,不要惧怕源码!!

     

    • 标签:
    • 进行
    • 方法
    • string
    • appendreplacement
    • 问题
    • 正则表达式
    • api
    • replacement
    • 匹配
    • group
    • reference.
  • 加入的知识群:
    学习元评论 (0条)

    评论为空
    聪明如你,不妨在这 发表你的看法与心得 ~



    登录之后可以发表学习元评论
      
暂无内容~~
顶部