“(? Pattern)” pattern is supported in Java

See English answers > regex named groups in java6

var pattern = @";(?<foo>\d{6});(?<bar>\d{6});";
var regex = new Regex(pattern,RegexOptions.None);
var match = regex.Match(";123456;123456;");

var foo = match.Groups["foo"].Success ? match.Groups["foo"].Value : null;
var bar = match.Groups["bar"].Success ? match.Groups["bar"].Value : null;

This seems to be a clean way to catch the group Can java do similar things, or do you need to grab groups according to the index location?

String foo = matcher.group(0);

Solution

This is supported from Java 7 Your c# code can be translated as follows:

String pattern = ";(?<foo>\\d{6});(?<bar>\\d{6});";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(";123456;123456;");
boolean success = matcher.find();

String foo = success ? matcher.group("foo") : null;
String bar = success ? matcher.group("bar") : null;

You must create a matcher object until you call find () to actually perform regular expression testing

(I use find () because it can find a match anywhere in the input string, such as regex Match() method If the regular expression matches the entire input string, then The matches () method returns only true)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>