gpt4 book ai didi

java - 如果模式为空,则打印空值

转载 作者:行者123 更新时间:2023-12-01 16:43:41 29 4
gpt4 key购买 nike

我有这个 Java 模式匹配代码:

                out.println("<tr>");
out.println("<td>" + file_path+ "</td>");
out.println("<td> .sql </td>");

Pattern pattern = Pattern.compile("(?<key>([\\w]+)?): (?<value>(.+)?)");
Matcher matcher = pattern.matcher(text);
while (matcher.find())
{
if (matcher.group("key").equals("author")) {
out.println("<td>" + matcher.group("value") + "</td>");
} else {
out.println("<td> N/A </td>");
}
}
out.println("<td> date </td>");

如果 matcher.groupmatcher 中没有找到值,你知道如何打印“N/A ”吗?目前表格单元格已被剪切。

最佳答案

看起来微不足道;设置一个 boolean 值:

out.println("<tr>");
out.println("<td>" + file_path+ "</td>");
out.println("<td> .sql </td>");

Pattern pattern = Pattern.compile("(?<key>([\\w]+)?): (?<value>(.+)?)");
Matcher matcher = pattern.matcher(text);
boolean noMatches = true;
while (matcher.find()) {
noMatches = false;
if (matcher.group("key").equals("author")) {
out.println("<td>" + matcher.group("value") + "</td>");
} else {
out.println("<td> N/A </td>");
}
}
if (noMatches) {
out.println("<td> N/A </td>");
}
out.println("<td> date </td>");

然后你可以清理它很多:

out.println("<tr>");
out.println("<td>" + file_path+ "</td>");
out.println("<td> .sql </td>");

Pattern pattern = Pattern.compile("author: (.*)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
out.println("<td>" + matcher.group(1) + "</td>");
} else {
out.println("<td> N/A </td>");
}
out.println("<td> date </td>");

关于java - 如果模式为空,则打印空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61816203/

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