我有一个问题,我似乎无法解决。 我只需要一段代码就可以在输入只有运算符左侧的数字时运行。 例如:如果输入为100+,则应运行代码。
但是如果输入是100-,100 *,100 /,100 ^等。
我还希望能够解析像-100 * 50这样的表达式。
如果问题不明确,我很抱歉。
I have a problem I can't seem to solve. I want a piece of code only to run when the input only has numbers on the left side of the operator. For example: If the input is 100+, then the code should run.
But also if the input is 100-, 100*, 100/, 100^ etc.
I also want to be able to parse expressions like -100*50.
I'm sorry if the question isn't clear.
最满意答案
此方法使用正则表达式 ,该正则表达式匹配以可选符号,可选空格,然后一个或多个数字,可选空格,运算符(在本例中为+ , - , * , /或^ )m开头的行。一个可选的标志,一个可选的空间,一个或多个数字,最后是可选的行尾。
public static void main(String[] args) { Pattern p = Pattern.compile("^\\-?\\s?\\d+\\s?[\\+\\-*\\/\\^]\\s?\\-?\\s?\\d+\\r?\\n?$"); System.out.println(p.matcher("123+").matches()); // outputs "true" System.out.println(p.matcher("123").matches()); // outputs "false" System.out.println(p.matcher("- 123123 *").matches()); // outputs "true" System.out.println(p.matcher("- 9843 * 23409").matches()); // outputs "true" }您也可以在线尝试并提供您自己的意见。
This method uses a Regular Expression that matches a line that starts with an optional - sign, an optinal space, then one or more numbers, an optional space, an operator (in this case, +, -, *, / or ^)m an optinal space, an optional - sign, an optinal space, then one or more numbers and finally, optional line endings.
public static void main(String[] args) { Pattern p = Pattern.compile("^\\-?\\s?\\d+\\s?[\\+\\-*\\/\\^]\\s?\\-?\\s?\\d+\\r?\\n?$"); System.out.println(p.matcher("123+").matches()); // outputs "true" System.out.println(p.matcher("123").matches()); // outputs "false" System.out.println(p.matcher("- 123123 *").matches()); // outputs "true" System.out.println(p.matcher("- 9843 * 23409").matches()); // outputs "true" }You can also try it online and provide your own input.
更多推荐
发布评论