java pattern matcher匹配最后一个数值

describe the method:

find->

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

start->The index of the first character matched

end->The offset after the last character matched

group->

Returns the input subsequence captured by the given group during the previous match operation.

For a matcher m, input sequence s, and group index g, the expressions m.group(g) and s.substring(m.start(g), m.end(g)) are equivalent.

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().

If the match was successful but the group specified failed to match any part of the input sequence, then null is returned. Note that some groups, for example (a*), match the empty string. This method will return the empty string when such a group successfully matches the empty string in the input.

之前的写法是:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {
	public static void main(String[] args) {
		Pattern p=Pattern.compile("_(\\d+)"); 
		Matcher m=p.matcher("a_3_4"); 
		System.out.println(m.find()); 
		System.out.println(m.start()); 
		System.out.println(m.end());
		System.out.println(m.group(1));
	}
}

输出结果:

true
1
3
3
 

但我想取出那个‘4’,所以用到了‘$'这个符号:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {
	public static void main(String[] args) {
		Pattern p=Pattern.compile("_(\\d+)$"); 
		Matcher m=p.matcher("a_3_4"); 
		System.out.println(m.find()); 
		System.out.println(m.start()); 
		System.out.println(m.end());
		System.out.println(m.group(1));
	}
}

运行结果:

true
3
5
4
 

转载于:https://my.oschina.net/ayyao/blog/894621

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值