日期:2014-05-20  浏览次数:21105 次

java给定前后字符串如何获取中间字符串

  如题

------解决方案--------------------
Java code

   String str="aaaaxxxxxxxxbbbb";
        String begin="aaaa";
        String end="bbbb";
        Matcher m=Pattern.compile("^"+begin+"(.*)"+end+"$").matcher(str);
        if(m.find())
            System.out.println(m.group(1));

------解决方案--------------------
Java code

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s="nimabi";
        String pre="ni";
        String suf="bi";
        System.out.println(s.substring((s.indexOf(pre)+pre.length()), s.indexOf(suf)));
    }

}

------解决方案--------------------
Java code
    static String getStr(String src,String beg,String end){
        String regex = beg+"(.*)"+end;
        System.out.println(regex);
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(src);
        if(m.find()){
            return m.group(1);
        }
        
        return null;
    }
    public static void main(String[] args)
    {
        System.out.println(getStr("aaa12121212dde", "aaa", "dde"));
    }

------解决方案--------------------
Java code
    public static void main(String[] args) {
        String s = "楼主你给我100分!";
        String mid = s.replaceAll(".*你(.*)!.*", "$1");
        System.out.println(mid);
    }

------解决方案--------------------
package com.xuyisen.socket.socket;

public class Test {

/**
* 截取字符串source中begin到end之间的字符串
* @param source 源字符串
* @param begin 开始
* @param end 结束
* @return
*/
public String subString(String source,String begin, String end){
String result = "";
if(!source.contains(begin)){
result = "源字符串中没有字符串: " + begin;
return result;
}else if(!source.contains(end)){
result = "源字符串中没有字符串: " + end;
return result;
}
int beginIndex = source.indexOf(begin);
int endIndex = source.indexOf(end);
result = source.substring(beginIndex+begin.length(), endIndex);
return result;
}

public static void main(String[] args) {
Test t = new Test();

String str = "louzhugeiwojiafen,ok";
String begin = "louzhu";
String end = ",ok";

String s = t.subString(str, begin, end);
System.out.println(s);
}
}