当前位置: 代码迷 >> J2SE >> Java 正则表达式,圣人请进!
  详细解决方案

Java 正则表达式,圣人请进!

热度:28   发布时间:2016-04-24 14:11:02.0
Java 正则表达式,高人请进!!
例:对于如下字符串:
"4.50XFLAX4.5 "   , "120.00YR   "
用正则表达式来区分这两种类型的字符串,
注:前面的是数字+字符+数字
        后面的是数字+字符
另外,对于前面的字符串要求取出“4.50XF”这部分,数值部分(4.50)是任意数值,字符部分(XF)是固定长度为2位的字符!

------解决方案--------------------
Pattern pattern1=Pattern.compile( "^(\\d+(\\.\\d+)?[A-Z]{2})[A-Z]*\\d+(\\.\\d+)?$ ");
Pattern pattern2 = Pattern.compile( "^\\d+(\\.\\d+)?[A-Z]{2}$ ");
String str1= "4.50XFLAX4.5 ";
String str2= "120.00YR ";
Matcher matcher=pattern1.matcher(str1);
if(matcher.matches()){
System.out.println( "1:\t "+matcher.group(1));
}
else{
matcher = pattern2.matcher(str1);
if(matcher.matches())
System.out.println(2);
}

matcher=pattern1.matcher(str2);
if(matcher.matches()){
System.out.println( "1:\t "+matcher.group(1));
}
else{
matcher = pattern2.matcher(str2);
if(matcher.matches())
System.out.println(2);
}
------解决方案--------------------
//两种情况都可以......
String str="4.50XFLAX4.5";
//String str="120.00YR"; 

String ptn = "((?<=[a-zA-Z])(?=[0-9|\\.]))|((?=[a-zA-Z])(?<=[0-9|\\.]))";
String[] s = str.split(ptn);
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
  相关解决方案