简体   繁体   中英

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?

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]+", "");  

你可能需要

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM