Java 如果字符串应包含';,则要匹配正则表达式';特定字符串前后
我使用以下表达式:Java 如果字符串应包含';,则要匹配正则表达式';特定字符串前后,java,regex,Java,Regex,我使用以下表达式: “?:(*);灰度=([0-9]{1,2}1[0-9]{2}2[0-4][0-9]| 25[0-5])(?:;\\w*)” 1。输入:灰度=(120)-->预期输出:真 2.输入:灰度=(120);-->预期输出:真 3.输入:灰度=(120);abcd-->预期输出:true 4.输入:灰度=(120)abcd-->预期输出:false 5.输入:abGRAYSCALE=(120);-->预期输出:false 6.输入:abc;灰度=(120);acx-->预期输出:真
“?:(*);灰度=([0-9]{1,2}1[0-9]{2}2[0-4][0-9]| 25[0-5])(?:;\\w*)”
1。输入:灰度=(120)-->预期输出:真
2.输入:灰度=(120);-->预期输出:真
3.输入:灰度=(120);abcd-->预期输出:true
4.输入:灰度=(120)abcd-->预期输出:false
5.输入:abGRAYSCALE=(120);-->预期输出:false
6.输入:abc;灰度=(120);acx-->预期输出:真
对于
1
-4
的情况,我得到了正确的输出,但对于5
和6
的情况,我没有得到正确的输出,而是在开头添加一个单词边界,并生成代码>首先作为可选项。您还必须添加模式以匹配开头和结尾括号
(.*?)\\b;?GRAYSCALE=\\(([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\)(?:;\\w*)?$
输出:
GRAYSCALE=(120) found? true
GRAYSCALE=(120); found? true
GRAYSCALE=(120);abcd found? true
GRAYSCALE=(120)abcd found? false
abGRAYSCALE=(120) found? false
abc;GRAYSCALE=(120);acx found? true
为什么要用一个正则表达式执行此操作?使用以下几种工具:
private static final Pattern SEMICOLON = Pattern.compile(";");
private static final Pattern GRAYSCALE
= Pattern.compile("GRAYSCALE=\\((\\d+\\))");
// Test...
final String[] splits = SEMICOLON.split(input);
Matcher matcher;
boolean found = false;
String inParens;
int number;
for (final String candidate: splits) {
matcher = GRAYSCALE.matcher(candidate);
if (!matcher.find())
continue;
inParens = matcher.group(1);
try {
number = Integer.parseInt(inParens);
break;
} catch (NumberFormatException e) {
// overflow
continue;
}
}
// test "number" here
如果您使用Java 8,这里有一些lambda滥用(上面定义了分号
和灰度
):
final opt=SEMICOLON.splitAsStream().map(灰度::匹配器)
.filter(Matcher::find).map(m->m.group(1)).findFirst();
如果(!opt.isPresent()){
//不走运
}
试一试{
parseInt(opt.get());
//至少找到一个整数
}捕获(数字格式){
//溢出
}
请发布正在工作的regex.regex:“?:(.*);灰度=([0-9]{1,2}| 1[0-9]{2}| 2[0-4][0-9]|25[0-5])(?:;\\w*)?”我得到了上述regex的正确输出。仅当我在GRAYSCALE之前添加任何内容时,返回false。这不能是有效的正则表达式。没有\\(
在其中。我不知道op在正则表达式上设置数字检查条件的原因是什么。@AvinashRaj我也是;看起来需要一个介于0和255之间的整数,这可以在正则表达式之外更有效地完成,这是肯定的
private static final Pattern SEMICOLON = Pattern.compile(";");
private static final Pattern GRAYSCALE
= Pattern.compile("GRAYSCALE=\\((\\d+\\))");
// Test...
final String[] splits = SEMICOLON.split(input);
Matcher matcher;
boolean found = false;
String inParens;
int number;
for (final String candidate: splits) {
matcher = GRAYSCALE.matcher(candidate);
if (!matcher.find())
continue;
inParens = matcher.group(1);
try {
number = Integer.parseInt(inParens);
break;
} catch (NumberFormatException e) {
// overflow
continue;
}
}
// test "number" here
final Optional<String> opt = SEMICOLON.splitAsStream().map(GRAYSCALE::matcher)
.filter(Matcher::find).map(m -> m.group(1)).findFirst();
if (!opt.isPresent()) {
// no luck
}
try {
Integer.parseInt(opt.get());
// Found at least an integer
} catch (NumberFormatException e) {
// overflow
}