gpt4 book ai didi

java - 使用 Vavr 获取正则表达式组

转载 作者:行者123 更新时间:2023-11-30 05:34:54 25 4
gpt4 key购买 nike

考虑到 Vavr 提供 tuples ,是否可以将它们用于 capturing groups在正则表达式中?

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

GET /resource HTTP 1.1

和匹配的模式

Pattern.compile("(\\w+) (.+) (.+)")

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

最佳答案

自己创建这个很容易:

/**
* 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();
}

这是您如何使用该方法:

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)));

关于java - 使用 Vavr 获取正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com