希望打印出所有下划线后边的字符串组合,如果有多个下划线,则需要分别打印出相应的组合(组合中也可能包括下划线)import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class javaTest {
static String code1 = "612162-thumb300";
static String code2 = "612162_2-thumb300";
static String code3 = "612162_23-thumb300";
static String code4 = "612162_2_2-thumb300";
public static void main(String args[])
{
Pattern p = Pattern.compile(".+\\_(.+)$");
Matcher m1 = p.matcher(code1);
Matcher m2 = p.matcher(code2);
Matcher m3 = p.matcher(code3);
Matcher m4 = p.matcher(code4);
while(m1.find()){
System.out.println("the SN for code 1 is "+m1.group(1));
}
while(m2.find()){
System.out.println("the SN for code 2 is "+m2.group(1));
}
while(m3.find()){
System.out.println("the SN for code 3 is "+m3.group(1));
}
while(m4.find()){
System.out.println("the SN for code 4 is "+m4.group(1));
}
}}
输出如下:
the SN for code 2 is 2-thumb300
the SN for code 3 is 23-thumb300
the SN for code 4 is 2-thumb300问题:无法匹配2_2-thumb300这个字符串
import java.util.regex.Pattern;
public class javaTest {
static String code1 = "612162-thumb300";
static String code2 = "612162_2-thumb300";
static String code3 = "612162_23-thumb300";
static String code4 = "612162_2_2-thumb300";
public static void main(String args[])
{
Pattern p = Pattern.compile(".+\\_(.+)$");
Matcher m1 = p.matcher(code1);
Matcher m2 = p.matcher(code2);
Matcher m3 = p.matcher(code3);
Matcher m4 = p.matcher(code4);
while(m1.find()){
System.out.println("the SN for code 1 is "+m1.group(1));
}
while(m2.find()){
System.out.println("the SN for code 2 is "+m2.group(1));
}
while(m3.find()){
System.out.println("the SN for code 3 is "+m3.group(1));
}
while(m4.find()){
System.out.println("the SN for code 4 is "+m4.group(1));
}
}}
输出如下:
the SN for code 2 is 2-thumb300
the SN for code 3 is 23-thumb300
the SN for code 4 is 2-thumb300问题:无法匹配2_2-thumb300这个字符串
Pattern p = Pattern.compile(".+\\_(.+)$");改成
Pattern p = Pattern.compile("[^_]+\\_(.+)$");
用string 自带的方法startsWith endWith就行了
Pattern p = Pattern.compile("_([^_]*)");要打印所有的就不要加后边界匹配"$"
static String code2 = "612162_2-thumb300";
static String code3 = "612162_23-thumb300";
static String code4 = "612162_2_2-thumb300";
public static void main(String args[])
{
String[] array={code1,code2,code3,code4};
Pattern p = Pattern.compile("(?<=_).*");
Matcher m =null;
for(String str:array){
m=p.matcher(str);
if(m.find()){
System.out.println(m.group());
}
}
}
Pattern p = Pattern.compile(".+?\\_(.+)$");
加了问号就只能找到
the SN for code 2 is 2-thumb300
the SN for code 3 is 23-thumb300
the SN for code 4 is 2_2-thumb300
反倒找不到
the SN for code 2 is 2-thumb300
the SN for code 3 is 23-thumb300
the SN for code 4 is 2-thumb300
不可能把code4的两种匹配都找出来么?