codeG
codeG

Reputation: 15

Remove leading special characters from multiline string

Working on XSS vulnerability in which I have a requirement to remove all the leading special characters only. No need to remove the special characters at the end or in between. Alphanumeric is allowed but no special characters at the beginning.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
        
public static void main(String args[])   {  
String str=   "**$*****Important****\n"
             + " document is not uploaded \n"
             + "%3Cscript%3E";    
str = str.replaceAll("[^a-zA-Z0-9\\s]", " ");  
System.out.println(str);  

 }  
}

The code above gives output as:

Important

But the expected output is:

Important**** document is not uploaded 3Cscript%3E

How can I fix this?

Upvotes: 0

Views: 333

Answers (2)

g00se
g00se

Reputation: 4296

You probably need

str = str.replaceAll("(?m)^[^a-zA-Z0-9\\s]+", " ");   

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83527

There are three changes you need to make:

  1. Anchor the match to the beginning of the string with ^.
  2. Match more than one special character with +.
  3. Replace the matched substring with "" instead of " ":
    str = str.replaceAll("^[^a-zA-Z0-9\\s]+", "");  

Upvotes: 2

Related Questions