【问题标题】:How to match line size with regex?如何将行大小与正则表达式匹配?
【发布时间】:2019-08-22 11:02:33
【问题描述】:

我有以下代码,试图匹配增加* 计数的金字塔,两边都被相同数量的空格包围。

//pyramid
var p = "     *     \n" +
        "    ***    \n" +
        "   *****   \n" +
        "  *******  \n" +
        " ********* \n" +
        "***********\n";
//not a pyramid - rows 2 and 3 do not increase in width
var np = "     *     \n" +
         "   *****   \n" +
         "   *****   \n" +
         "  *******  \n" +
         " ********* \n" +
         "***********\n";
//pyramid with more width variation, non-point top
var pspace = "          **          \n" +
             "         ****         \n" +
             "      **********      \n" +
             "    **************    \n" +
             "   ****************   \n" +
             "**********************\n";
final var REGEX = "((?<S>\\s*)(?<star>\\**)\\k<S>\\R(?=$|((?<S2>\\s*)(?<extra>\\*+)\\k<star>\\k<extra>\\k<S2>\\R)))+";
System.out.println("p is a pyramid: "+Pattern.matches(REGEX, p));
System.out.println("np is a pyramid: "+Pattern.matches(REGEX, np));
System.out.println("pspace is a pyramid: "+Pattern.matches(REGEX, pspace));

输出:

p 是一个金字塔:是的
np 是一个金字塔:假
pspace 是一个金字塔:是的

我要做的最后一件事是确保输入字符串的所有“行”长度相等。在这一点上,我完全陷入困境,因为除了固定长度的字符串边界(即X{min, max})之外我真的找不到任何东西。所以,这就是我想知道的:

  1. 如何确保我的字符串中的所有行都是金字塔(从第一行到最后一行增加星数(完成),由新行分隔(完成),在空格内居中(完成),并且相等长度线 (???))?
  2. 如何简化正则表达式以减少命名捕获组的过度使用?

【问题讨论】:

  • 老实说,确定传入周期的建议高度和宽度可能更容易,然后在代码中生成正确的周期,并将该字符串与输入进行比较。
  • @TimBiegeleisen 我知道在没有正则表达式的情况下计算它可能会更容易。我想知道 Java 正则表达式是否有能力做到这一点,或者我是否应该放弃尝试找到一种方法。

标签: java regex


【解决方案1】:

正则表达式无法完成您尝试完成的计数类型,因此您必须使用混合策略。在换行符边界上分解字符串,然后使用正则表达式匹配前导和尾随空格以及它们之间的星号。但是您必须通过使用length 对象拥有的length 方法查看这些字符串的长度,来查看这些匹配项的长度是否满足您的要求:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class test
{
    public static void main(String[] args) {
        String p = "     *     \n" +
                   "    ***    \n" +
                   "   *****   \n" +
                   "  *******  \n" +
                   " ********* \n" +
                   "***********\n";
        String[] lines = p.split("\n");
        Pattern pattern = Pattern.compile("^(\\s*)(\\*+)(\\s*)$");
        int lastLength = 0;
        boolean isPyramid = true;
        for (String line : lines) {
            Matcher m = pattern.matcher(line);
            m.find();
            String spaces1 = m.group(1);
            String spaces2 = m.group(3);
            String asterisks = m.group(2);
            int len = asterisks.length();
            if (len <= lastLength || spaces1.length() != spaces2.length()) {
                isPyramid = false;
                break;
            }
            else {
                lastLength = len;
            }
        }
        System.out.println("p is a pyramid: " + isPyramid);    
    }
}

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2016-02-16
    • 2014-01-27
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多