Agarta Agarta - 2 months ago 16
Java Question

regex.PatternSyntaxException meta character '*'

Scanner input = new Scanner(;
String girdi = input.nextLine();
for(int i=1; i<girdi.length(); i+=1){
if(girdi.charAt(i) == '*'){
int temp1= girdi.charAt(i-1)-'0';
int temp2= girdi.charAt(i+1)-'0';
int temp3 = temp1 * temp2;
String a = girdi.substring(i-1,i);
String b = "" + temp3;
String a2 = girdi.substring(i+1,i+2);
String b2 = girdi.substring(i , i+1);
girdi = girdi.replaceFirst(a,b);
girdi = girdi.replaceFirst(b2, "");
girdi = girdi.replaceFirst(a2, "");

ı am just trying to make multiplication

when I type someting like that (3*5) give me that error :

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

and when I am using backslah to escape :

if(s.charAt(i) == '\\*'){

I see unclosed chracter literal and illegal start of expression errors

what should I do ?


Refer to the Javadoc of String.replaceFirst:

  • The first parameter is a regular expression (meaning characters like * have special meaning);
  • The second parameter is a regex replacement (meaning certain character sequences have special meaning, e.g. \ and $).

If you want to pass in strings from an untrusted source (like user input), you need to quote them appropriately:

girdi = girdi.replaceFirst(Pattern.quote(a), Matcher.quoteReplacement(b));