Jakkie Chan
Jakkie Chan

Reputation: 317

Regex illegal escape character

String[] tokens = infix.split("[0-9]*([.][0-9]+)? | sin | cos | tan | log | \^ | sqrt | \( | \) | \+ | \- | \* | \/");

When I compile this, it says I have an illegal escape character at "\^", I'm trying to tell it to ignore the special character "^" and view "^" as an actual String, don't I have the syntax right?

Upvotes: 0

Views: 1571

Answers (1)

Bohemian
Bohemian

Reputation: 425003

In java, you need to escape the escapes. Essentially, you must use double backslashes for string literals:

String[] tokens = infix.split("[0-9]*([.][0-9]+)? | sin | cos | tan | log | \\^ | sqrt | \\( | \\) | \\+ | \\- | \\* | /");

Note that you don't escape forward slashes in java (regex or not).

As an aside, you regex may be simplified to:

String[] tokens = infix.split("[0-9]*([.][0-9]+)? | sin | cos | tan | log | sqrt | [()+*-] | /");

Upvotes: 3

Related Questions