public static String cut(String html,String a,String b)
{ String truncated_html=html; int ai=html.indexOf(a); if (ai>-1) { truncated_html=html.substring(ai+a.length()); int bi=truncated_html.indexOf(b); if (bi>-1) { truncated_html=truncated_html.substring(0, bi); } } return truncated_html; }
原先的版本
参考
import org.apache.commons.lang.StringUtils;
下的substringBetween
后来的版本
public static String cut(String html,String a,String b)
{ //String range="()"//[)()[] String truncated_html=html; if (html==null) { truncated_html=""; return truncated_html; } if (a==null && b==null) { return truncated_html; } if (a!=null && b==null) { int ai=html.indexOf(a); if (ai>-1) { truncated_html=html.substring(ai+a.length()); } return truncated_html; } if(a==null && b!=null) { int bi=html.indexOf(b); if (bi>-1) { truncated_html=html.substring(0,bi); } return truncated_html; } int ai=html.indexOf(a); if (ai>-1) { // truncated_html=html.substring(ai+a.length()); int bi=html.indexOf(b, ai+a.length());// System.out.println("bi:"+String.valueOf(bi)); if (bi>-1) { truncated_html=html.substring(ai+a.length(), bi); } else { truncated_html=html.substring(ai+a.length()); } } return truncated_html; }}
@Test
public void CutTest() { String html="abcdefgzzdfadf"; Assert.assertEquals("efg", StringUtils.cut(html,"cd","zz")); Assert.assertEquals("efgzzdfadf",StringUtils.cut(html,"cd","yy")); Assert.assertEquals(html,StringUtils.cut(html,"u","yy")); Assert.assertEquals("abc",StringUtils.cut(html,null,"d")); Assert.assertEquals(html,StringUtils.cut(html,null,null)); Assert.assertEquals("dfadf",StringUtils.cut(html,"zz",null)); html="\" id=\"J_SpanLimitProm\">158.72</strong>元</li>"; try{ Double price=Double.parseDouble(StringUtils.cut(html,"J_SpanLimitProm\">","</strong>元")); System.out.println(price); Assert.assertEquals(158.72D, price); } catch(Exception ex) { System.out.println(ex.toString()); } }