如何检查字符串是否仅含运算符?正则表达式非法字符范围报错排查
Hey there! Let's break down what's going wrong with your regex and get your operator validation logic sorted out.
1. Why the "Illegal character range" Error Happens
That error pops up because in your regex [(+=-*/^)]+, the sequence =-* is being interpreted as a character range. The ASCII value of = is 61, and * is 42—so you're trying to define a range from a higher value to a lower one, which regex engines don't allow.
2. Fixing the Regex
There are two simple ways to fix this:
- Move the
-to the start or end of your character set, so it's not treated as a range operator:[(+*/^=-)] - Escape the
-with a backslash (remember, in Java strings you need double backslashes):"[(+\\-*/^=)]+"
3. Implementing the Full Operator-Only Check
Your current code only checks if the stack top matches the regex, but let's make sure we properly validate that a string contains only your target operators (no extra characters). Here's a revised version of your code with the fix and improved logic:
import java.util.Stack; public class StringConverter { private Stack<String> stringStack = new Stack<>(); private Stack<Double> digitStack = new Stack<>(); public void convertString(String s) { String[] arr = s.split("\""); for (String segment : arr) { stringStack.push(segment); } // Fixed regex: placed '-' at the end to avoid range issues String operatorRegex = "[(+*/^=-)]+"; if (!stringStack.isEmpty()) { String topElement = stringStack.peek(); if (topElement.matches("[0-9]+")) { digitStack.push(Double.valueOf(stringStack.pop())); } else if (topElement.matches(operatorRegex)) { // Add your operator handling logic here (e.g., push to operator stack) System.out.println("Top element is a valid operator string: " + topElement); } else { System.out.println("Top element is neither a digit nor valid operators"); } } System.out.println("Digit stack contents: " + digitStack); } // Helper method to check if any string is made up of only your operators public boolean isOnlyOperators(String input) { if (input == null || input.isBlank()) { return false; // Adjust this if empty string should be considered valid } String operatorRegex = "[(+*/^=-)]+"; return input.matches(operatorRegex); } }
Quick Notes
- The
matches()method in Java automatically checks the entire string (it's equivalent to wrapping your regex in^and$), so you don't need to add those anchors manually. - If you need to add/remove operators later, just update the characters inside the
[]in the regex. - Characters like
+,*,/don't need escaping inside a regex character set—only-(when not at the edges),^(when at the start),[, and]require special handling.
内容的提问来源于stack exchange,提问作者Dartweiler

