Search code examples
javaregexstringreplaceall

Regex for matching with space in a string


I need to append a prefix infront of some text, with space in between the text and the prefix.

For Example: "Sample text" will become "[EXTERNAL] Sample text".

If the prefix is already contained in the text (case-insensitive) then I need to replace the prefix with all caps case.

For example if the text is: "[External] Sample" or "[External]Sample" or "[EXTERNAL]Sample":

In all cases I need to have "[EXTERNAL] Sample" with space in between the prefix and the sample text.

    private static final String TITLE_REGEX_PATTERN = "(?i)"+ Pattern.quote("[external]");
    private static final String EXTERNAL_TITLE_PREFIX = "[EXTERNAL] ";



private String appendPrefixToTitle(String title) {
        if (!titleContainsPrefix(title)) {
            return "[EXTERNAL] " + title;
        } else {
            return title.replaceFirst(TITLE_REGEX_PATTERN, EXTERNAL_TITLE_PREFIX);
        }
    }

private boolean titleContainsPrefix(String title) {
        return StringUtils.beginsWithIgnoreCase(title, EXTERNAL_TITLE_PREFIX.trim());
    }

Doing this will add an extra space if the title already contains correct format. Suggest me a better approach without splitting hte input.


Solution

  • Try this code to replace the possible [External] at the beginning of the text

    String text = "[External]Sample";
    text = Pattern.compile("(^\\[EXTERNAL\\]\\s*)?", Pattern.CASE_INSENSITIVE).matcher(text).replaceFirst("[EXTERNAL] ");