这可能不是最有效的,但它会工作......
\$([^\s]*)(?:[A-Z]\d)|\$([^\s]*)
它之所以有效,是因为第一组找到所有那些有 Capitol 后跟数字的人……而第二组找到所有没有后缀的人……
如果您从捕获组中获得匹配项,那就是您想要的。
我认为这样的事情会奏效......
import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class HereYouGo {
public static void main (String args[]) {
String input = "$mytestA1 --> expected output: mytest\r\n$againD4 --> expected output: again\r\n$something --> expected output: something\r\n$name3 --> expected output: name3 // because there was no capital letter before the number digit\r\n$name2P4 --> expected output: name2\r\n";
Pattern myPattern = Pattern.compile("\\$([^ ]*)(?:[A-Z]\\d)|\\$([^ ]*)", Pattern.DOTALL | Pattern.MULTILINE);
Matcher myMatcher = myPattern.matcher(input);
while(myMatcher.find())
{
String group1 = myMatcher.group(1);
String group2 = myMatcher.group(2);
//note: this should probably be changed in the case neither match is found
System.out.println( group1!=null? group1 : group2 );
}
}
}
这将输出以下内容
mytest
again
something
name3
name2