正则表达式获得完整的可选部分(如果存在)

时间:2015-07-20 15:47:22

标签: javascript regex

我需要验证输入的订单号是原件还是重复件。

订单号可以是数字或字符,且必须为13 @Override public void load(Properties props, InputStream is) throws IOException { Tika tika = new Tika(); String type = tika.detect(is); if (!type.equals("text/plain")) { try { byte[] cipherText = IOUtils.toByteArray(is); ByteBuffer cipherTextBlob = ByteBuffer.wrap(cipherText); logger.info("cipherTextBlob: " + cipherTextBlob); DecryptRequest decryptReq = new DecryptRequest().withCiphertextBlob(cipherTextBlob); awsCredentials = new BasicAWSCredentials(AWS_KMS_KEY, AWS_KMS_SECRET); amazonKMSClient = new AWSKMSClient(awsCredentials).withRegion(...some region...); DecryptResult decryptResult = amazonKMSClient.decrypt(decryptReq); String fileContents = new String(decryptResult.getPlaintext().array()); props.load(new StringReader(fileContents)); logger.info("props: " + props); super.load(props, is); } catch (Exception e) { logger.error("e: ", e); } } else { super.load(props, is); } }

副本,由破折号分隔,并添加一个大写字母([A-Z0-9]{13})

鉴于用户可以输入原始订单或重复订单,副本可以存在或不存在,所以,到目前为止,我有这个

([-]{1}[A-Z]{1})

它工作正常,但我有一个问题验证,当输入重复时,它已完成且正确

([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}

我在最后3个场景得到正确验证方面遇到了问题

我仍在努力弄清楚如何制作,如果可选部分存在,那么它的完整和正确https://regex101.com/r/wU4tQ5/3

2 个答案:

答案 0 :(得分:3)

这里存在一些问题。首先,您不需要{0,1}作为可选案例,您只需使用?[-]{1}也可以- {{1}而且你需要使用开始和结束锚点来匹配你的字符串从头到尾以拒绝匹配某些字符串,如[A-Z]{1}

[A-Z]

请参阅演示https://regex101.com/r/kD2wN2/1

答案 1 :(得分:1)

试试这个正则表达式

(^[a-zA-Z0-9]{13}(?:[-]{1}[A-Z]{1}){0,1}$)