public class SubString {
//用于处理字符串的类
public static String getString(String src, String target) {
//获得target在源字符串src中最后一次出现位置之前的内容
return src.substring(0, src.lastIndexOf(target));
}
//用于测试
public static void main(String[] args) {
// TODO Auto-generated method stub
String target = "部";//设定target为"部"
//获取所需的字符串
String result = getString("小卖部", target);//为了和谐..
System.err.println(result);
}
}
输出结果:
小卖
该方法同样适用于多个字,比如管理部门,将target设置为"部门"时,程序的运行结果会是"管理"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ttts {
public static void main(String... strs) {
String str = "VVV4BC3233BBB";
System.out.println(getStrings(new StringBuilder(),str));
}
public static String getStrings(StringBuilder sb,String str) {
if (str == null)return "";
if (str.equals(""))return sb.toString();
Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*");
Matcher m = p.matcher(str);
if (m.find()) {
String group = m.group();
sb.append(group);
String subStr = str.substring(group.length());
Pattern pattern = Pattern.compile(".*\d+.*");
if (pattern.matcher(subStr).matches()) {
getStrings(sb,str.substring(group.length()));
}
}
return sb.toString();
}
}
以上是提取字符串前缀的Java方法的详细内容。更多信息请关注PHP中文网其他相关文章!