我正在使用:
Pattern.compile("^[0-9w?]")
它应该同时允许:12345678
、12345678-00001
你能提出一个有效的模式吗?
对于您显示的示例,您可以尝试以下操作吗。
^d+(?:-d+)?$
这是上面regex 的在线演示
解释:添加以上详细解释。
^d+ ##Checking if value starts from digits(1 or more occurrences) here.
(?: ##Starting a non capturing group from here.
-d+ ##Checking if it has -(hyphen) and followed by 1 or more digits.
)?$ ##Closing non capturing group here and keeping it optional to match OP's both cases at the end of the value.