0

I am implementing calculator with java.

So, I tried this:

If end of the string is not '+', '-', '*', '/', or '(', then add '+' at the end of the string.

So, I tried following code (assume that variable s is 12345+):

if(!s.matches("[-(+*/]$"))
   s+="+";

But, the if statement(s.matches("[-(+-*/]$")) does not return true, am I wrong?? It works on linux's bash shell well.

A.Cho
  • 571
  • 1
  • 6
  • 17
  • 1
    `String#matches` requires a full string match. See http://stackoverflow.com/questions/30912978/java-regex-pattern-that-matches-in-any-online-tester-but-doesnt-in-eclipse – Wiktor Stribiżew Mar 18 '16 at 15:46
  • Also, `-` has special meaning inside a character class (`[]`), so `+-*` means all characters from `+` to `*` and since `+` is ASCII 43 and `*` is ASCII 42, that's an inverted range, and will either fail or match nothing. – Andreas Mar 18 '16 at 15:49
  • ah, sorry my mistake, `[-+*/]$` doesn't work too – A.Cho Mar 18 '16 at 15:51
  • Why not just do it a proper java way without regex? – user1231232141214124 Mar 18 '16 at 15:52
  • @Wiktro Stribizew Then, Can't it be possible with other regex?? – A.Cho Mar 18 '16 at 15:53
  • @redFIVE Why is a non-regex way more proper than regex? It would definitely require a lot more code that using regex, so regex is "cleaner" / more concise. – Andreas Mar 18 '16 at 15:53
  • @redFIVE dummy-looking code is made because of many if statements – A.Cho Mar 18 '16 at 15:54
  • @Andreas, maybe not cleaner, but certainly less troubleshooting required. – user1231232141214124 Mar 18 '16 at 15:54
  • 1
    @A.Cho Sure it's possible. Drop the anchor (`$`) since it's meaningless when using `matches()`, and make it `".*[-(+*/]"` – Andreas Mar 18 '16 at 15:55
  • @Andreas: Or `"(?s).*[-(+*/]"` (if there can be a newline, but I guess there is not) – Wiktor Stribiżew Mar 18 '16 at 15:57
  • @redFIVE I disagree. A non-regex way would be to get the last character `x.charAt(x.length()-1)` and compare that to the 5 characters under consideration. The pitfall there is the empty string, so it is no less error-prone than regex. – Andreas Mar 18 '16 at 15:58

0 Answers0