简体   繁体   English

Java Regex:根据特定模式评估字符串

[英]Java Regex: Evaluate a string against a particular pattern

I have strings of a particular pattern as below which i need to validate: 我有以下需要验证的特定模式的字符串:

String a ="test/<value>"
String b = "test/test1/<value>"
String c = "test3";
String d = "test4"

where value - can be any thing ie alphabets,numeric,symbol,spl characters. 其中的 -可以是任何东西,即字母,数字,符号,spl字符。

String c and String d are pretty straight forward.The issue comes for string a,b. 字符串c和字符串d非常简单,问题出在字符串a,b。

Valid Strings: 有效字符串:

test/12 | test/abc | test/12.39 ...
test/test1/12 | test/test1/abc | test/test1/12.30
test3
test4

Invalid Strings: 无效的字符串:

test1/12
test/test123/12

test,test1,test3,test4 are key words. test,test1,test3,test4是关键字。 any change in that should return me false. 对此的任何更改都应使我返回错误。

I tried with the below regex pattern: 我尝试使用以下正则表达式模式:

Pattern  pattern1 = "^(test/(test1/)?[A-Za-z0-9]+|test3|test4)?/?$"

it works fine for few scenario's ie 它适用于少数情况,即

test/123 (pass)
test/test1/abc123(pass)

It fails when it has any symbol,decimal value or spl characters: 有任何符号,十进制值或spl字符时,它将失败:

test/10.12 (Fail)
test/test1/@#$$ (Fail)

Pattern pattern2 = "^(test/(test1/)?[A-Za-z0-9/*!@#$%^&*()\"{}_|\\?/<>,.]+|test3|test4)?/?$";

When i use the above pattern if there are any change in the keyword it fails. 当我使用上述模式时,如果关键字有任何更改,它将失败。

test/test1344/123(Fail)

ie even if i change the keyword it returns as true.Expected result is false. 即,即使我更改关键字,它也会返回true。预期结果为false。

Please advice as to how i can validate the above strings ? 请咨询我如何验证上述字符串?

You can use this regex: 您可以使用此正则表达式:

^(?:test/(?:test1/)?[^/]+|test3|test4)/?$

I just replaced [A-Za-z0-9] by [^/] (any non forward slash character) 我刚刚用[A-Za-z0-9] [^/] (任何非正斜杠字符)替换了[A-Za-z0-9]

尝试^(test3|test4|test(/test1)?/([0-9.]+|[A-Za-z]+))$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM