ael*_*nes 11 java regex matcher
我想知道Java是否与C#的命名模式匹配相当.例如,在C#中,我可以这样做:
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;
Run Code Online (Sandbox Code Playgroud)
这似乎是一种抓住群体的干净方式.Java可以做类似的事情,还是我需要根据索引位置抓取组?
String foo = matcher.group(0);
Run Code Online (Sandbox Code Playgroud)
mat*_*tts 17
从Java 7开始支持此功能.你的C#代码可以翻译成这样的代码:
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;
Run Code Online (Sandbox Code Playgroud)
Matcher
在调用之前,您必须创建一个实际上不执行正则表达式测试的对象find()
.
(我find()
之所以使用它是因为它可以在输入字符串中的任何地方找到匹配项,就像Regex.Match()
方法一样..matches()
如果正则表达式匹配整个输入字符串,该方法只返回true.)
归档时间: |
|
查看次数: |
13556 次 |
最近记录: |