How to add features missing from the Java regex implementation?

前端 未结 5 1776
暖寄归人
暖寄归人 2020-11-28 03:03

I\'m new to Java. As a .Net developer, I\'m very much used to the Regex class in .Net. The Java implementation of Regex (Regular Expressions) is no

5条回答
  •  鱼传尺愫
    2020-11-28 03:54

    One can rant, or one can simply write:

    public class Regex {
    
        /**
         * @param source 
         *        the string to scan
         * @param pattern
         *        the regular expression to scan for
         * @return the matched 
         */
        public static Iterable matches(final String source, final String pattern) {
            final Pattern p = Pattern.compile(pattern);
            final Matcher m = p.matcher(source);
            return new Iterable() {
                @Override
                public Iterator iterator() {
                    return new Iterator() {
                        @Override
                        public boolean hasNext() {
                            return m.find();
                        }
                        @Override
                        public String next() {
                            return source.substring(m.start(), m.end());
                        }    
                        @Override
                        public void remove() {
                            throw new UnsupportedOperationException();
                        }
                    };
                }
            };
        }
    
    }
    

    Used as you wish:

    public class RegexTest {
    
        @Test
        public void test() {
           String source = "The colour of my bag matches the color of my shirt!";
           String pattern = "colou?r";
           for (String match : Regex.matches(source, pattern)) {
               System.out.println(match);
           }
        }
    }
    

提交回复
热议问题