[英]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:我正在尝试检查用户输入的字符串是否为有效表达式:
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 个或多个空格)*
: End non-capture group. )*
: 结束非捕获组。 Repeat this group 0 or more times
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.