当前位置: 代码迷 >> J2EE >> 关于字符串内查寻指定值~indexOf除外的
  详细解决方案

关于字符串内查寻指定值~indexOf除外的

热度:86   发布时间:2016-04-17 23:45:26.0
关于字符串内查找指定值~indexOf除外的
String str ="1,32,44,21,43,12,33";  这样的字符串
String eq ='1';  这是需要查找的值

如果用  indexof 来查找会 出现一个问题  就是不是我想要的也会出现    比如  21 12 这不是我想要的  我只要 1 这样

目前还没想到好的方法 可以 更快速的查找出来  
我这边使用的是  字符分割  再去比对  
String[] st = str.split(",");
for(int i=0;i<st.length;i++){
  if(eq.equals(st[i])){
   return true;
}
}

请问各位大神有其他更方便的方法吗?   
类似 mysql中的    find_in_set 函数的功能
这样 能少写 for循环    因为 在这个循环内  外面已经嵌套了 好几个for循环了。
------解决方案--------------------
引用:
^(1)[,]

用正则也是可以的(这个思路还是蛮好的),但是这个正则表达式不行,只能匹配第一个是1的字符串
可以这样
	public static void main(String[] args) {
// TODO Auto-generated method stub

String str="21,32,44,43,12,33,1,333,112";
//比如查找1
String regex1="\\b1\\b";
Pattern p = Pattern.compile(regex1);
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group());
}

}

\\b1\\b


  相关解决方案