Java正则表达式API系列

本文详细介绍了Java中正则表达式的使用,包括Pattern.LITERAL和Pattern.MULTILINE模式,以及Matcher类的方法如索引、Study和Replacement。通过示例展示了如何在不同模式下匹配和替换文本。
摘要由CSDN通过智能技术生成

默认情况下,当我们使用“.”时表达式中,我们将匹配输入字符串中的每个字符,直到遇到新行字符。

使用此标志,匹配也将包括行终止符。我们将通过以下示例更好地理解。这些例子将略有不同。由于我们感兴趣的是针对匹配的字符串进行断言,因此我们将使用matcher的group方法来返回之前的匹配。

首先,我们将看到默认行为:

@Test
public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
    Pattern pattern = Pattern.compile("(.*)");
    Matcher matcher = pattern.matcher(
      "this is a text" + System.getProperty("line.separator") 
        + " continued on another line");
    matcher.find();
 
    assertEquals("this is a text", matcher.group(1));
}

正如我们所看到的,只有行终止符之前输入的第一部分匹配。

现在在dotall模式下,包括行终止符在内的整个文本都将匹配:

@Test
public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
    Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(
      "this is a text" + System.getProperty("line.separator") 
        + " continued on another line");
    matcher.find();
    assertEquals(
      "this is a text" + System.getProperty("line.separator") 
        + " continued on another line", matcher.group(1));
}

我们还可以使用嵌入的标志表达式来启用dotall模式:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值