java regular expressions memo

Recently upper frame and the scene to be processed normally reptiles and replacement string matching, memo.

Non-greedy mode

For example, to a mating connector html text, for example a href = "www.abc.com/xyz/o" need to be replaced a href = "www.bing.com?q=o", may be as follows:

    static final String OSCHINA_LINK = "\"(https://www\\.abc\\.net/p/)(.+)\"";
    static Pattern pattern = Pattern.compile(OSCHINA_LINK);
    static String BING_SEARCH = "\"https://cn.bing.com/search?q=$2";

But this time will result in the first href "text after the last" = contents are links between the address, because the regular java default greedy mode . To the first "on the end, you need non-greedy mode, that is, plus, as follows?:

    static final String OSCHINA_LINK = "\"(https://www\\.abc\\.net/p/)(.+?)\"";
    static Pattern pattern = Pattern.compile(OSCHINA_LINK);
    static String BING_SEARCH = "\"https://cn.bing.com/search?q=$2";
        Matcher m = pattern.matcher(param.getData().getNewsBody());
        SB StringBuffer = new new StringBuffer ();
         // use the find () method to find the first match of the object 
        boolean the Result = m.find ();
         // . Use cycle will sentence all the tables to find out and replaced with the user name list name, and the contents added to sb in 
        the while (the Result) {
            m.appendReplacement(sb, BING_SEARCH);
            // next continue to find a matching object 
            the Result = m.find ();
        }
        // last call appendTail () method to the last matched string was added to the residual in sb; 
        m.appendTail (sb);

Packet replacement

Another scenario is to add the prefix before any given keyword, such as "abc, bcf, wdf" replaced "x.abc, x.bcf, x.wdf", where the list of keywords from the input given .

This time we need to replace the grouping, grouped with (). as follows:

Tel = String "18,304,072,984" ;
 // brackets indicate group, is replaced by $ n represents the contents of the first part of n sets of 
tel = tel.replaceAll ( "(\\ d {3}) \\ d {4} (\\ d {4}) "," $ 2 $ 1 **** " );
System.out.print(tel);   // output: 183****2984

String one = "hello girl hi hot".replaceFirst("(\\w+)\\s+(\\w+)", "a.$2 a.$1"); 
String two = "hello girl hi hot".replaceAll("(\\w+)\\s+(\\w+)", "a.$2 a.$1"); 
System.out.println(one);   // a.girl a.hello hi hot
System.out.println(two);   // a.girl a.hello a.hot a.hi

 

Guess you like

Origin www.cnblogs.com/zhjh256/p/11025456.html