首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Vavr获取正则表达式组

用Vavr获取正则表达式组
EN

Stack Overflow用户
提问于 2019-07-02 14:51:30
回答 1查看 223关注 0票数 1

考虑到Vavr提供了元组,在正则表达式中可以将它们用于捕获组吗?

以HTTP请求行为示例字符串进行匹配

获取/resource HTTP1.1

和一个匹配的模式

代码语言:javascript
复制
Pattern.compile("(\\w+) (.+) (.+)")

Vavr中是否有将三个匹配字符串作为元组返回的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-02 14:51:30

很容易自己创建:

代码语言:javascript
复制
/**
 * Gets the three matched groups of the {@code regex} from the {@code original}.
 *
 * @param regex    a {@link Pattern} that should have three groups in it and
                   match the {@code original}
 * @param original the string we'll match with the {@code regex}
 * @return a {@link Tuple3} of the three matched groups or {@link Option#none} if
 *         the {@code regex} did not match
 */
static Option<Tuple3<String, String, String>> getGroups3(Pattern regex,
                                                         CharSequence original) {
    var matcher = regex.matcher(original);
    return matcher.matches() && matcher.groupCount() == 3 ?
            Some(Tuple.of(matcher.group(1), matcher.group(2), matcher.group(3))) :
            Option.none();
}

以下是使用该方法的方法:

代码语言:javascript
复制
var pattern = Pattern.compile("(\\w+) (.+) (.+)");
var requestLine = "GET /resource HTTP 1.1";

var result = getGroups3(pattern, requestLine).fold(
        // No match
        () -> String.format("Could not parse request method, resource, and " +
                        "HTTP version from request line. Request line is '%s'",
                requestLine),
        // Do whatever you want with the three matched strings
        tuple3 -> tuple3.apply((method, resource, httpVersion) ->
                String.format("Method is %s, resource is %s, HTTP version is %s",
                        method, resource, httpVersion)));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56855090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档