[英]Regular Expression Java Pattern
I should match two numbers bigger than 0 separated from a whitespace 我应该匹配两个大于0的数字,并用空格隔开
^\\d+?\\s\\d+?$
I tried that but it clearly doesn't work then I should also match a string that begins with # and ends with # and inside there should be a fixed amount of char, that can be any char, determined by a variable w - 2. 我尝试了一下,但显然不起作用,然后我还应该匹配一个以#开头并以#结尾的字符串,并且在其中应该有固定数量的char,可以是任何char,由变量w-2确定。
String regex = "#.{" + (w - 2) + "}$";
return Pattern.matches(regex, stringToMatch );
tried that but doesnt work. 尝试过,但没有用。
The most efficient way (I know ;) to match a non-zero number, while asserting it's a valid number and allowing for leading zeroes, is 断言它是有效数字并允许前导零的同时,它是匹配非零数字的最有效方法(我知道;)。
\d*[1-9]\d*
This makes sure all tested characters are digits and at least one of them isn't a zero. 这样可以确保所有测试的字符都是数字,并且其中至少一个不是零。
So your first declaration should be something like 所以你的第一个声明应该像
String regex = "^\\d*[1-9]\\d*\\s\\d*[1-9]\\d*$";
(You could do similar things with look-around, but they're less effective - especially for longer numbers.) (您可以使用环顾四周功能做类似的事情,但效果不佳-特别是对于较长的数字。)
As for the second part of your question, as mentioned in comments, you've forgotten the ending #
. 至于问题的第二部分,如注释中所述,您已经忘记了结尾的
#
。 If it's allowed to be preceded and followed by other text: 如果允许在其他文本之前和之后:
String regex = "#.{" + (w - 2) + "}#";
If it should be the only text: 如果应该是唯一的文本:
String regex = "^#.{" + (w - 2) + "}#$";
Hope this helps. 希望这可以帮助。
Regards 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.