-1

Javaでテキストを正当化するメソッドを実行したいです。そのためには、任意のスペース文字に一致し、それらを 2 つのスペースに 1 つずつ置き換える必要がある正規表現が必要です。1 つのスペースがない場合は、2 つのスペースを検索して 3 つにする必要があり、2 つのスペースがない場合は、3 つのスペースを検索して 4 つのスペースにする必要があります。これが続く…

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 に答える