使用纯Java编写正则表达式的开源库包

16-07-22 banq
    

regex-builder是一个围绕java.util.regex的轻量包装器,能够让你使用普通Java代码编写正则表达式,而不是非透明的正则字符串,这样更具有可读性和重用性。

导入包即可使用:

import sgreben.regex_builder.CaptureGroup;
import sgreben.regex_builder.Expression;
import sgreben.regex_builder.Re;
<p>

以日期为案例:

正则字符串是:

^(\d\d\)/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d):(\d\d)$
<p>

而java代码是:

Expression twoDigits = Re.sequence(Re.digit(), Re.digit());
Expression fourDigits = Re.repeat(Re.digit(), 4);
Expression slash = Re.character('/');
Expression colon = Re.character(':');
Expression space = Re.character(' ');
CaptureGroup day = Re.capture(twoDigits);
CaptureGroup month = Re.capture(twoDigits);
CaptureGroup year = Re.capture(fourDigits);
CaptureGroup hour = Re.capture(twoDigits);
CaptureGroup minute = Re.capture(twoDigits);
CaptureGroup second = Re.capture(twoDigits);
Expression dateExpression = Re.sequence(
  Re.beginLine(),
  day, slash, month, slash, year, space, // DD/MM/YYY
  hour, colon, minute, colon, second,    // HH:MM:SS
  Re.endLine(),
);
<p>

调用上面的代码:

Pattern p = Re.compile(dateExpression)
Matcher m = p.matcher("01/05/2015 12:30:22");
m.find();
assertEquals("01", m.group(day));
assertEquals("05", m.group(month));
assertEquals("2015", m.group(year));
assertEquals("12", m.group(hour));
assertEquals("30", m.group(minute));
assertEquals("22", m.group(second));
<p>

sgreben/regex-builder: Write regular expressions i