I'm trying to check if a user-entered string is a valid expression:
So far my current code userInput.matches("[0-9(+*\\-\\s)]+")
can process requirements 1-4. How can I modify my regex to meet criteria 5 and 6?
You may use this code:
bool valid = userInput.matches("\\d+(?:\\h*[+*-]\\h*\\d+)*");
If you want to allow signed -
numbers then use:
bool valid = userInput.matches("-?\\d+(?:\\h*[+*-]\\h*-?\\d+)*");
If there can be leading/trailing spaces then use:
bool valid = userInput
.matches("\\h*-?\\d+(?:\\h*[+*-]\\h*-?\\d+)*\\h*");
Breakup:
\\d+
: Match 1+ digits (?:
: Start non-capture group
\\h*
: Match 0 or more whitespaces [+*-]
: Match +
or *
or -
\\h*
: Match 0 or more whitespaces )*
: End non-capture group. Repeat this group 0 or more times
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.