1

I have a below string in Java

String text = "<link href=\"https://example.com\" rel=\"stylesheet\" type=\"text/css\" /> <link href=\"https://example.com\" rel=\"stylesheet\" type=\"text/css\" /> <div class=\"fr-view\"> <div></div><p>analyst</p> </div>";

Expected Output:

text = <link href='https://example.com' rel='stylesheet' type='text/css' /> <link href='https://example.com' rel='stylesheet' type='text/css' /> <div class='fr-view'> <div></div><p>analyst</p> </div>

Basically I want to replace the html attributed in double quotes with single quotes. I have used below regex which works perfectly but I get the sonar issue.

text.replaceAll("\\p{Cntrl}|\"|\\\\", "'");

Sonar issue I am facing with above regex is "Single-character alternations in regular expressions should be replaced with character classes".

Can anyone suggest the alternate regex to achieve the same.

Thanks

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
palpras
  • 39
  • 9
  • I think it means you should express the alternatives as `"[\\p{Cntrl}\"\\\\]"` but I'm not sure. I haven't seen this particular Sonar message before. – Dawood ibn Kareem Oct 18 '22 at 18:05
  • Why do you look for \ and control characters in your regex at all? To replace a quote character you just have to look for exactly that one, you wouldn't even have to use a regular expression for that. – cyberbrain Oct 18 '22 at 19:46

1 Answers1

1

You have a "\\p{Cntrl}|\"|\\\\" string literal. It represents the following regex - \p{Cntrl}|"|\\ that matches any control character, or a double quotation mark, or a backslash.

In order to resolve the "Single-character alternations in regular expressions should be replaced with character classes" issue, you need to place these three elements into a character class, i.e. in between [...]:

text.replaceAll("[\\p{Cntrl}\"\\\\]", "'");

Now, it represents a [\p{Cntrl}"\\] pattern that matches the same three chars as before, but more efficiently.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563