无法从字符串

时间:2015-05-19 06:08:40

标签: java udf

我在java中为区域转换程序创建了一个Udf函数。我有以下数据:

230Sq.feet
110Sq.yards
8Acres
123Sq.Ft

我想将上述数据拆分为:

230 Sq.feet
990 Sq.feet
344 Sq.feet
123 Sq.feet

我尝试了以下代码:

public class Areaconversion2 extends EvalFunc<String> {

public String determine_Area (String input) throws IOException
{
    String[] AreaArr = input.split("");
    Double Area;

    if(AreaArr[1].equalsIgnoreCase("Sq.Yards") || AreaArr[1].equalsIgnoreCase("Sq.Yds")) 
    {
    Area = Double.parseDouble(AreaArr[0]);
        Area = Area * 9;
        String Ar = Area.toString() + " Sq.Feet";
        return Ar;
    }
else if(AreaArr[1].equalsIgnoreCase("Acre") || AreaArr[1].equalsIgnoreCase("Acres")) 
{      
        Area = Double.parseDouble(AreaArr[0]);
        Area = Area * 43560;
        String Ar = Area.toString() + " Sq.Feet";
    return Ar;
 }
else if(AreaArr[1].equalsIgnoreCase("Sq.Feet)")||AreaArr[1].equalsIgnoreCase("Sq.Ft"));
      {
          Area = Double.parseDouble(AreaArr[0]); 
       String Ar = Area.toString() + " Sq.Feet";
          return Ar;
      }

    }

public String exec(Tuple input) throws IOException {
    // TODO Auto-generated method stub
     if (input == null || input.size() == 0)
         return null;

     try

     {

         String str = (String)input.get(0);

         return determine_Area(str);
         }catch(Exception e){
              throw new IOException("Caught exception processing input row ", e);
         }
}

}

我只在处理时得到了例外。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以选择split()Pattern,而不是Matcher

public static void main(String[] args) {
    String s = "230Sq.feet";
    Pattern p = Pattern.compile("(\\d+)(\\D+)"); // group 1 is the number part and group 2 is everything that follows the number part
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
        System.out.println(m.group(2));
    }
}
O/P :
230
Sq.feet

答案 1 :(得分:0)

您可以使用前瞻/后视匹配:

String[] fields = str.split("(?<=\\d)(?=[A-Z])");

(?<=\\d)是零长度匹配器,意味着&#34;数字必须在&#34;之前,而(?=[A-Z])是零长度匹配器,意味着&#34;大写字母必须在匹配的字符串&#34;。

之后

根据您的数据进行测试:

public static void main(String[] args) {
    String[] inputs = {"230Sq.feet", "110Sq.yards", "8Acres", "123Sq.Ft"};
    for(String input : inputs) {
        String[] fields = input.split("(?<=\\d)(?=[A-Z])");
        System.out.println(fields[0]+" "+fields[1]);
    }
}

输出结果为:

230 Sq.feet
110 Sq.yards
8 Acres
123 Sq.Ft