-1

I used regex101 to make my expression, and it looks like this using their symbols

\d+ [+-\/*] \d*

Basically I want a user to enter like 123 + 123 but the entire statement is one string with exactly one space after the first number and one space after the operator

The above expression works, but It doesn't convert the same into Java.

I thought these symbols were universal, but I guess not. Any ideas how to convert this to the proper syntax?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DDisciple
  • 177
  • 1
  • 10
  • `\\d+ [+-\\/*] \\d*` \ needs to be escaped in java... – brso05 Apr 26 '19 at 18:28
  • `"123 + 123".matches("^\\d+ [+-\\/*] \\d*$")` is true. Sounds like your character class should be `[-+/*]` so that the `-` isn't interpreted as a range, but other than that, what specifically is the problem that you're seeing? Can you add some code and example data or errors? – that other guy Apr 26 '19 at 18:30

2 Answers2

2

Regular expressions are not universal. In general, no two regular expression systems are the same.

Java does not have regular expressions. Some Java classes support regular expressions. The Pattern class defines the regular expressions that are used by some Java classes including Matcher which seems likely to be the class you are using.

As already identified in the comments, \ is the escape-the-next-character character in Java. If you want to represent \ in a String, you must use \\. For example, \d in a regular expression must be written \\d in a Java String.

DwB
  • 37,124
  • 11
  • 56
  • 82
1

You can simply use groups () and design a RegEx as you wish. This RegEx might be one way to do so:

((\d+\s)(\+|\-)(\s\d+))

It has four groups, and you can simply call the entire input using $1:

enter image description here

You can also escape \ those required language-based chars.

Emma
  • 27,428
  • 11
  • 44
  • 69