3

I would like to match a line with a regular expression. The line contains two numbers which could be divided by plus, minus or a star (multiplication). However, I am not sure how to escape the star.

line.matches("[0-9]*[+-*][0-9]*");

I tried also line.matches("[0-9]*[+-\\*][0-9]*"); but it does not work either.

Should I put the star into separate group? Why does the escaping \\* not work in this case?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Smajl
  • 7,555
  • 29
  • 108
  • 179

1 Answers1

7

* is not metacharacter in character class ([...]) so you don't need to escape it at all. What you need to escape is - because inside character class it is responsible for creating range of characters like [a-z].

So instead of "[+-*]" which represents all characters placed in Unicode Table between + and * use

  • "[+\\-*]"
  • or place - where it can't be used as range indicator
    • at start of character class [-+*]
    • at end of character class [+*-]
    • or right after other range if you have one [a-z-+*]

BTW if you would like to add \ literal to your operators you need to write it in regex as \\ (it is metacharacter used for escaping or to access standard character classes like \w so we also need to escape it). But since \ is also special in String literals (it can be used to represent characters via \n \r \t or \uXXXX), you also need to escape it there as well. So in regex \ needs to be represented as \\ which as string literal is written as "\\\\".

BTW 2: to represent digit instead of [0-9] you can use \d (written in string literal as "\\d" since \ is special there and requires escaping).

BTW 3: if you want to make sure that there will be at least two numbers in string (one on each side of operator) you need to use + instead of * at [0-9]* since + represents one or more occurrence of previous element, while * represents zero or more occurrences.

So your code can look like

line.matches("\\d+[-+*]\\d+");
Pshemo
  • 122,468
  • 25
  • 185
  • 269