How do we remove special characters from a string from a particular position in java?

103 Views Asked by At

I have a scenario where i have to remove special characters from a string.

Input String : name=/"xyz =bcd .olm --=myname/"

Output String Must be Like: name=/"xyz bcd olm myname/"

I tried something like below and still not able to come up with the exact regex. Can anyone help me to figure out what i have done wrong?

    String inputString = "name=\"xyz =bcd .olm --=myname\"";
    String regex = "(?<=name=\")[^<]*(?<!/)(\\w+)(?=[^>]*>)";
    String outputString = inputString.replaceAll(regex, "$1");

    System.out.println(outputString);
2

There are 2 best solutions below

0
ChivalrouS On

For the replacement. You need to first get the content value of name field. Then you can remove special characters from the string.

Example code block:

    String line = "name=\"xyz =bcd .olm --=myname\"";
    Pattern pattern = Pattern.compile("name=\"(.*)\"");
    Matcher matcher = pattern.matcher(line);
    if (matcher.find()) {
        String nameString = matcher.group(1);
        String newNameString = nameString.replaceAll("[^A-Za-z0-9 ]", "");
        String result = line.replace(nameString, newNameString);
        System.out.println(result);
    }

Result prints as name="xyz bcd olm myname"

0
Wiktor Stribiżew On

You can use

inputString.replaceAll("(\\G(?!^)|name=\")([^\"\\p{Punct}]*)\\p{Punct}(?=[^\"]*\")", "$1$2")

See the regex demo

The regex matches

  • (\G(?!^)|name=\") - Group 1: name=" or the end of the preceding successful match
  • ([^\"\p{Punct}]*) - Group 2: any zero or more chars other than " and punctuation chars
  • \p{Punct} - any punctuation chars
  • (?=[^\"]*\") - immediately from the current position to the right, there must be any zero or more chars other than " and then a " char.