java 正则 不包含,Java字符串 - 获取(但不包括)两个正则表达式之间的所有内容?...

该博客讨论了在Java中如何通过指定正则表达式的分隔符来提取子字符串,而不包括分隔符本身。示例代码展示了一个方法,使用`Pattern`和`Matcher`类,配合`DOTALL`模式匹配包含换行符的子串。
摘要由CSDN通过智能技术生成

In Java, is there a simple way to extract a substring by specifying the regular expression delimiters on either side, without including the delimiters in the final substring?

For example, if I have a string like this:

Header text

what is the easiest way to extract the substring:

Header text

Please note that the substring may contain line breaks...

thanks!

解决方案

Write a regex like this:

"(regex1)(.*)(regex2)"

... and pull out the middle group from the matcher (to handle newlines in your pattern you want to use Pattern.DOTALL).

Using your example we can write a program like:

package test;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Regex {

public static void main(String[] args) {

Pattern p = Pattern.compile(

"(.*)",

Pattern.DOTALL

);

Matcher matcher = p.matcher(

"Header\n\n\ntext"

);

if(matcher.matches()){

System.out.println(matcher.group(1));

}

}

}

Which when run prints out:

Header

text

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值