简体   繁体   English

用于检查字符串是否仅包含数字和运算符(但没有 2 个连续运算符)的正则表达式

[英]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]不能有任何字母 [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)不能有两个连续的运算符(因此“123 ++ 456”无效)
  6. An operator must be followed by digits ("123 + " would be invalid but "345678 * 6" would be okay)运算符后必须跟数字(“123 +”无效,但“345678 * 6”可以)

So far my current code userInput.matches("[0-9(+*\\-\\s)]+") can process requirements 1-4.到目前为止,我当前的代码userInput.matches("[0-9(+*\\-\\s)]+")可以处理要求 1-4。 How can I modify my regex to meet criteria 5 and 6?如何修改我的正则表达式以满足标准 5 和 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 \\d+ :匹配 1+ 个数字
  • (?: : Start non-capture group (?: : 启动非捕获组
    • \\h* : Match 0 or more whitespaces \\h* :匹配 0 个或多个空格
    • [+*-] : Match + or * or - [+*-] :匹配+*-
    • \\h* : Match 0 or more whitespaces \\h* :匹配 0 个或多个空格
    • \d+`: Match 1+ digits \d+`:匹配 1+ 个数字
  • )* : End non-capture group. )* : 结束非捕获组。 Repeat this group 0 or more times重复此组 0 次或多次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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