简体   繁体   中英

Regex expression to check if a string only contains digits and operators (but no 2 consecutive operators)

I'm trying to check if a user-entered string is a valid expression:

  1. There can't be any letters [a-zA-z]
  2. We're only dealing with integers
  3. Spaces are allowed
  4. The only valid operators are '+', '-', and '*' (no dividing)
  5. There can't be two consecutive operators (so "123 ++ 456" would be invalid)
  6. An operator must be followed by digits ("123 + " would be invalid but "345678 * 6" would be okay)

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
    • \d+`: Match 1+ digits
  • )* : 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM