Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在分号分隔的数字列表中查找数字的正则表达式模式_Java_Regex - Fatal编程技术网

Java 在分号分隔的数字列表中查找数字的正则表达式模式

Java 在分号分隔的数字列表中查找数字的正则表达式模式,java,regex,Java,Regex,我需要写一个正则表达式,这样我就可以看到temp是否存在于包含中,所以我写了一个这样的regexpatern String temp = "77"; // It can be 0 or 100 or any value // So the pattern will be like this only but number can be change anytime String inclusion = "100;0;77;200;....;90"; 那么您认为这个正则表达式每次都能工作吗?或

我需要写一个正则表达式,这样我就可以看到temp是否存在于包含中,所以我写了一个这样的regexpatern

String temp = "77"; // It can be 0 or 100 or any value

// So the pattern will be like this only but number can be change anytime
String inclusion = "100;0;77;200;....;90";
那么您认为这个正则表达式每次都能工作吗?或者这个正则表达式有问题吗

// This is the regular Expression I wrote.
String regexPattern = "(^|.*;)" + temp + "(;.*|$)"; 

如果
temp
可以包含正则表达式的特殊字符,您可能会遇到问题,但如果它始终是整数,那么您的方法应该可以

但是,更直接的方法是在分号上拆分字符串,然后查看结果数组中是否有
temp

如果您坚持使用正则表达式,您可以通过删除
*
,将其简化一点,以下操作与当前正则表达式的工作方式相同:

if(inclusion.matches(regexPattern)) {

}

edit:Oops,上述内容实际上不起作用,我对Java中的正则表达式有点不熟悉,没有意识到整个字符串需要匹配,谢谢

您不需要正则表达式:

"(^|;)" + temp + "(;|$)"

没有正则表达式的另一种选择

temp = "77"
String searchPattern = ";" + temp + ";";
String inclusion = ";" + "100;0;77;200;....;90" + ";";
inclusion.indexOf(searchPattern);

当然,这里没有模式识别(通配符等)

如果temp是7,inclusion只包含77但不包含7怎么办?我还想知道一件事。为什么有些人说使用正则表达式的替代方法。一般来说,正则表达式不好用吗?正则表达式是一个非常强大的工具,我非常喜欢并使用它。但我也从比我聪明的人身上学到,使用最简单的工具来完成工作往往更好。这也是个人喜好的问题。不管你喜欢哪一种,我都会选择F.J.的
split
方法。需要时应该使用正则表达式。在这种情况下,我认为@alan是对的,你不需要使用正则表达式。正则表达式比搜索子字符串涉及更多的字符串处理,它将更慢,更难编码,更容易暴露于潜在的错误。这就是为什么我在前后添加“;”的原因。仔细阅读,这并不能取代他现有的代码。如果你在
matches()
上看到javadco,这很棘手。我还想知道一件事。为什么有些人说使用正则表达式的替代方法。一般来说,正则表达式不好用吗?@user1419563-regex非常适合某些事情,但一般来说,我认为人们觉得正则表达式很难阅读和维护,并且认为如果有合理的替代方法,应该避免使用正则表达式。
String inclusion2 = ";" + inclusion + ";";  // To ensure that all number are between semicolons
if (inclusion2.indexOf(";" + temp + ";") =! -1) {
   // found
}