2

Хочу отформатировать строку:

about 90 percent of all children attend public school, which is free ... the other 10 percent go I private schools,Which often include religious education.

и получить на выходе такую строку:

About 90 percent of all children attend public school, which is free... The other 10 percent go I private schools, which often include religious education.

Вышло заменить первую букву в выражении на большую, дальше не могу разобраться. Код:

private static final String STRING = "about 90 percent of all children attend public school, which is free ... the other 10 percent go I private schools,Which often include religious education.";

private static final String REGEX = "(?:^| )^[a-z]";

public static void main(String[] args){
    Matcher matcher = Pattern.compile(REGEX).matcher(STRING);
    StringBuffer stringBuffer = new StringBuffer();

    while (matcher.find()){
        matcher.appendReplacement(stringBuffer, matcher.group().toUpperCase());
    }
    matcher.appendTail(stringBuffer);
    System.out.println(stringBuffer.toString());
}
2
  • 1
    Объясните что на что по какому алгоритму нужно заменить. 26 дек 2018 в 11:17
  • @Эникейщик, по факту строку нужно просто отредактировать. 1) Большая буква после точки, все остальные прописными. 2) Убрать пробелы перед разделительными знаками(добавить после).
    – UjinUkr
    26 дек 2018 в 11:22

2 ответа 2

0

Работает, если текст на латинице:

       String s = "about 90 percent of all children attend public school, which is free ... the other 10 percent go I private schools,Which often include religious education. `";

    Pattern pattern = Pattern.compile("\\.\\s[a-z]|,[A-Z]|\\s`|\\s\\.{3}\\s");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()){
        String item = matcher.group();
        s = item.matches("\\.\\s[a-z]") ? s.replaceAll(item, item.toUpperCase()) :
                item.matches(",[A-Z]") ? s.replaceAll(item, item.substring(0,1).concat(" ").concat(item.substring(1,2).toLowerCase())) :
                        item.matches("\\s`") ? s.replaceAll(item, "") :
                                item.matches("\\s\\.{3}\\s") ? s.replaceAll("\\s\\.{3}\\s", "... ") : "";
    }

    s = s.substring(0, 1).toUpperCase() + s.substring(1);

About 90 percent of all children attend public school, which is free... the other 10 percent go I private schools, which often include religious education.

6
  • Перед многоточием символ пробела остался.
    – UjinUkr
    26 дек 2018 в 11:28
  • А сами не хотите поработать над этим?
    – alex
    26 дек 2018 в 11:28
  • я добавил вариант с многоточием
    – alex
    26 дек 2018 в 12:03
  • что бы разобраться скопировал ваш код и собрал, получил следующее: About 90 percent of... children attend public school, which is free... the other 10 percent go I private schools, which often include religious education.
    – UjinUkr
    26 дек 2018 в 12:51
  • да. странно. не могу понять в чём проблема
    – alex
    26 дек 2018 в 14:21
0

Немного разобравшись написал нужный функционал. Написано каряво, поэтому буду рад если укажите как можно упростить и оптимизировать код.

private static final String COMA_REGEX = "\\s*,\\s*";
private static final String DOT_REGEX = "\\s*(?<!\\.)\\.(?!\\.)\\s*";
private static final String MULTI_DOT_REGEX = "\\s*\\.{3}\\s*";
private static final String APOSTROPHE_REGEX = "\\s*'\\s*";
private static final String FORMAT_CASE = "((?:^| )^\\w" + "|" + MULTI_DOT_REGEX + "\\w" + "|" + DOT_REGEX + "\\w)";

private static final String COMA_REPLACEMENT = ", ";
private static final String MULTI_DOT_REPLACEMENT = "... ";
private static final String DOT_REPLACEMENT = ".";
private static final String APOSTROPHE_REPLACEMENT = "'";

public static void main(String[] args){
    String buffer = "";
    buffer = SECOND_STRING.replaceAll(COMA_REGEX, COMA_REPLACEMENT);
    buffer = buffer.replaceAll(DOT_REGEX, DOT_REPLACEMENT);
    buffer = buffer.replaceAll(MULTI_DOT_REGEX, MULTI_DOT_REPLACEMENT);
    buffer = buffer.replaceAll(APOSTROPHE_REGEX, APOSTROPHE_REPLACEMENT);

    buffer = getFormatCaseString(buffer);
    System.out.println(buffer);
}

private static String getFormatCaseString(String targetString){
    Matcher matcher = Pattern.compile(FORMAT_CASE).matcher(targetString);
    StringBuffer stringBuffer = new StringBuffer();

    while (matcher.find()){
        matcher.appendReplacement(stringBuffer, matcher.group().toUpperCase());
    }
    matcher.appendTail(stringBuffer);
    return stringBuffer.toString();
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.