contains()可以不可以传一个正则表达式进去?如果不能的话,String有什么方法可以去匹配某一个String里面是否包含某个规则的字符串?

解决方案 »

  1.   

    楼主要实现什么样的功能呢?是不是像这样:
    String a = "[abc]";
    String b = "[ac]";
    a.contains(b);返回true?
      

  2.   

    有很多string 在这些string当中,我需要匹配一个特定的字符串,如果符合,然后返回这个string。所以我学要匹配该String是否满足我的要求,但是那个特定的字符串不是简单的abc就可以的,需要一个正则表达式去匹配
      

  3.   

    比如说我这个String里面必须包含"Driver\A"或者“Driver\B"等等。
    我可以使用if(string.contains("Driver\\A") || string.contains("Driver\\B"))这样的表达式,我就是想问这样的表达式可否用if(string.contains(正则表达式))去代替,如果不能的话,有什么样的方法比较好
      

  4.   

    那你使用 match 方法不就可以了。
      

  5.   

    呵呵,写错了是 matches,这里可以用正则表达式
      

  6.   

    比如说像这样...让人难受的"\"public class Test67 {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] as = { "Driver\\A", "whatever1", "Driver\\B", "whatever2" };
    for (String s : as) {
    if (s.matches("Driver\\\\[A-Z]"))
    System.out.println(s);
    }
    }
    }
      

  7.   

    matches是需要整个string都match,还是只要其中一部分match就可以了?
      

  8.   

    String的matches是匹配整个,如果要一部分,可以按下面这样import java.util.regex.*;public class Test67 {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] as = { "Driver\\A", "whatever1", "aaDriver\\B", "whatever2" };
    Pattern p = Pattern.compile("Driver\\\\[A-Z]");
    Matcher m;
    for (String s : as) {
    m = p.matcher(s);
    if (m.find())
    System.out.println(s);
    }
    }
    }
      

  9.   

    matches是需要整个string都match,还是只要其中一部分match就可以了?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~这个我也不确定。。但是我会马上去查api,,不是来这里等人回答
      

  10.   

    /**
         * Returns true if and only if this string contains the specified
         * sequence of char values.
         *
         * @param s the sequence to search for
         * @return true if this string contains <code>s</code>, false otherwise
         * @throws NullPointerException if <code>s</code> is <code>null</code>
         * @since 1.5
         */
        public boolean contains(CharSequence s) {
            return indexOf(s.toString()) > -1;
        }
      

  11.   

    matchers 是匹配整个字符串,你前后加个 .* 就可以了。String[] as = { "Driver\\A", "whatever1", "aaDriver\\B", "abDriver\\Ccc", "whatever2" };
    for(String str : as) {
    if(str.matches(".*Driver\\\\[A-Z].*")) {
    System.out.println(str);
    }
    }