java pattern 提取文字,Java正则表达式在标记之间提取文本

I have a file with some custom tags and I'd like to write a regular expression to extract the string between the tags. For example if my tag is:

[customtag]String I want to extract[/customtag]

How would I write a regular expression to extract only the string between the tags. This code seems like a step in the right direction:

Pattern p = Pattern.compile("[customtag](.+?)[/customtag]");

Matcher m = p.matcher("[customtag]String I want to extract[/customtag]");

Not sure what to do next. Any ideas? Thanks.

解决方案

You're on the right track. Now you just need to extract the desired group, as follows:

final Pattern pattern = Pattern.compile("(.+?)", Pattern.DOTALL);

final Matcher matcher = pattern.matcher("String I want to extract");

matcher.find();

System.out.println(matcher.group(1)); // Prints String I want to extract

If you want to extract multiple hits, try this:

public static void main(String[] args) {

final String str = "applehelloorangepear";

System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]

}

private static final Pattern TAG_REGEX = Pattern.compile("(.+?)", Pattern.DOTALL);

private static List getTagValues(final String str) {

final List tagValues = new ArrayList();

final Matcher matcher = TAG_REGEX.matcher(str);

while (matcher.find()) {

tagValues.add(matcher.group(1));

}

return tagValues;

}

However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值