-1

我想做一个方法来证明java中的文本。为此,我需要一个必须匹配任何空格字符的正则表达式,然后将它们一一替换为两个空格。如果没有一个空格,则它必须搜索两个空格并将它们变为三个,如果没有两个空格,则它必须搜索三个空格并将它们变为四个空格。这继续……

java中的正则表达式如何做到这一点?

我使用 replaceFirst(String regex, String replacement) 方法。

4

2 回答 2

1

试试这个:

Pattern p = Pattern.compile("(\\s+)");
Matcher m = p.matcher(input);
if (m.find()) {
    input = m.replaceAll("$1 ");
}
System.out.println(input);

使用上面的代码:

"How can   I do  that with regex?" 

变成

"How  can    I  do   that  with  regex?"
于 2013-02-27T05:34:22.787 回答
1

你可能走错路了。这是我将如何做到这一点:

public static String addSpaces (String string, int desiredLength)
{
    String [] parts = string.trim ().split ("\\s+");

    int l = parts.length;

    if (l <= 1)
        return string; // Cannot add spaces because there is only one word
    else
    {
        int count = 0;
        for (String part: parts)
            count += part.length ();

        count = desiredLength - count;

        if (count < 0) count = 0;

        int n = count / (l - 1);
        int k = count % (l - 1);

        StringBuilder result = new StringBuilder (parts [0]);
        for (int i = 0; i < l - 1; i++)
        {
            int m = i < k ? n + 1 : n;

            for (int j = 0; j < m; j++)
                result.append (' ');

            result.append (parts [i + 1]);
        }

        return result.toString ();
    }
}

public static void main (String [] args)
{
    System.out.println (addSpaces ("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec est ligula, porta", 80));
    System.out.println (addSpaces ("quis feugiat eget, congue ac odio. Curabitur in purus mi, nec feugiat velit. Ut", 80));
    System.out.println (addSpaces ("pulvinar massa vel risus fringilla adipiscing. Aliquam fringilla congue mi, eget", 80));
    System.out.println (addSpaces ("consectetur nibh egestas at. In hac habitasse platea dictumst. Nullam interdum", 80));
    System.out.println (addSpaces ("rutrum laoreet. Etiam vestibulum diam dui. Phasellus erat sapien, pulvinar vel", 80));
    System.out.println (addSpaces ("rutrum eu, accumsan vel ante. Etiam odio erat, commodo eu rutrum eu, molestie id", 80));
    System.out.println (addSpaces ("tellus. Ut eu ante ipsum. Cras pretium bibendum nisi a rhoncus. Lorem ipsum", 80));
    System.out.println (addSpaces ("dolor sit amet, consectetur adipiscing elit. Etiam porta, urna non placerat", 80));
    System.out.println (addSpaces ("rutrum, velit enim aliquet arcu, non vehicula sem mauris non dui. Quisque est", 80));
    System.out.println (addSpaces ("nisi, facilisis non pretium et, luctus in nisi. Ut sed luctus enim. Maecenas", 80));
    System.out.println ("vitae lorem vel justo aliquet consectetur.");
}

输出是:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec est ligula, porta
quis  feugiat eget, congue ac odio. Curabitur in purus mi, nec feugiat velit. Ut
pulvinar massa vel risus fringilla adipiscing. Aliquam fringilla congue mi, eget
consectetur  nibh  egestas at. In hac habitasse platea dictumst. Nullam interdum
rutrum  laoreet.  Etiam vestibulum diam dui. Phasellus erat sapien, pulvinar vel
rutrum eu, accumsan vel ante. Etiam odio erat, commodo eu rutrum eu, molestie id
tellus.  Ut  eu  ante  ipsum.  Cras pretium bibendum nisi a rhoncus. Lorem ipsum
dolor  sit  amet,  consectetur  adipiscing  elit. Etiam porta, urna non placerat
rutrum,  velit  enim  aliquet arcu, non vehicula sem mauris non dui. Quisque est
nisi,  facilisis  non  pretium  et, luctus in nisi. Ut sed luctus enim. Maecenas
vitae lorem vel justo aliquet consectetur.

以下是如何将文本拆分为行然后证明:

public static String addSpaces (String [] words, int count)
{
    int l = words.length;

    if (l == 0)
        return "";
    else if (l == 1)
        return words [0];
    else
    {
        int n = count / (l - 1);
        int k = count % (l - 1);

        StringBuilder result = new StringBuilder (words [0]);
        for (int i = 0; i < l - 1; i++)
        {
            result.append(' ');

            int m = i < k ? n + 1 : n;

            for (int j = 0; j < m; j++)
                result.append (' ');

            result.append (words [i + 1]);
        }

        return result.toString ();
    }
}

public static String [] justify (String string, int width)
{
    List<String> result = new ArrayList<String>();

    String [] words = string.trim ().split ("\\s+");

    int n = 0;
    List<String> line = new ArrayList<String>();
    for (String word: words)
    {
        if (!line.isEmpty () && n + word.length () > width)
        {
            result.add (
                addSpaces (
                    line.toArray (
                        new String [line.size ()]), 
                    Math.max (0, width - n)));

            line.clear ();
            n = 0;
        }

        line.add (word);
        if (n > 0)
            n += 1;
        n += word.length();
    }

    result.add (addSpaces (line.toArray (new String [line.size ()]), 0));
    return result.toArray(new String [result.size ()]);
}

public static void main (String [] args)
{
    String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut porta bibendum ipsum vitae pretium. Nulla facilisi. Aenean eu orci eget diam bibendum lobortis. Nulla nisl ante, consectetur feugiat tincidunt eget, venenatis a velit. Nullam eget justo pellentesque diam commodo pharetra imperdiet ut tellus. Maecenas massa mi, placerat et vestibulum non, luctus ut nulla. Nam id libero vel massa malesuada commodo vel nec magna. Maecenas faucibus fermentum nisi et mattis.";
    String [] lines = justify (text, 80);
    for (String line: lines)
        System.out.println (line);
}

输出是:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut porta bibendum ipsum
vitae pretium. Nulla facilisi. Aenean eu orci eget diam bibendum lobortis. Nulla
nisl  ante,  consectetur  feugiat tincidunt eget, venenatis a velit. Nullam eget
justo pellentesque diam commodo pharetra imperdiet ut tellus. Maecenas massa mi,
placerat  et  vestibulum non, luctus ut nulla. Nam id libero vel massa malesuada
commodo vel nec magna. Maecenas faucibus fermentum nisi et mattis.
于 2013-02-27T05:39:22.723 回答