0

I am trying to check for multiple conditions, between DATA, data, dAta, daTa, datA etc.

and replace any of these with "Data". How can I do that?

    private String removeBrackets(final String line)
    {
        String lowerCaseData = null;
        String removeLeft = line.replace("[", "");
        String removeRight = removeLeft.replace("]", "");
        if (removeRight.contains("Data"))
        {
            lowerCaseData = removeRight.replace("Data", "data");
            return Character.toUpperCase(lowerCaseData.charAt(0)) + lowerCaseData.substring(1);
        }
        else
        return Character.toUpperCase(removeRight.charAt(0)) + removeRight.substring(1);
    }
Anonymous
  • 47
  • 7

2 Answers2

2

You can work with Java Regular Expressions (RegEx) and the replaceAll(String regex, String replacement) function.

Basically, you replace - case insensitive - all "data" (or "DAta", "DATA", "data" and so on...) with "Data".

private String removeBrackets(final String line)
{
    return line.replaceAll("(?i)data", "Data");
}

which outputs (when the input is not more than "data" in any case):

"Data"

In general, it's this principle:

String input = "FOODATAFOO";
output = input.replaceAll("(?i)data", "Data");
System.out.println(output);

which outputs:

FOODataFOO

I found the solution in this Stack Overflow question: How to replace case-insensitive literal substrings in Java

This is a link to the w3schools, where you can learn about RegEx in Java: https://www.w3schools.com/java/java_regex.asp

You can learn more about the "i Modifier" of RegEx here [it's in JavaScript, but the modifier functionality is the same]: https://www.w3schools.com/jsref/jsref_regexp_i.asp

Here are some informations about the replaceAll() method: https://www.javatpoint.com/java-string-replaceall

Thomi
  • 194
  • 1
  • 2
  • 12
1

Try it like this. The (?i) is a flag that says ignore case.

String s = "Other text Data daTa DATA data dATa";
s = s.replaceAll("(?i)data", "Data");
System.out.println(s);

prints

Other text Data Data Data Data Data
WJS
  • 36,363
  • 4
  • 24
  • 39