【问题标题】:not able to split the number value from the string无法从字符串中拆分数字值
【发布时间】:2015-05-19 06:08:40
【问题描述】:

我正在为 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);
         }
}

}

我只在处理时遇到了异常。任何帮助将不胜感激。

【问题讨论】:

  • 请跟踪异常?
  • 8Acres 呢??
  • String[] AreaArr = input.split("");它永远不会拆分你的字符串。

标签: java udf


【解决方案1】:

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

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

(?&lt;=\\d) 是零长度匹配器,意思是“一个数字必须在前面”,(?=[A-Z]) 是零长度匹配器,意思是“一个大写字母必须在匹配的字符串之后”。

对您的数据进行了测试:

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

【讨论】:

    【解决方案2】:

    您可以使用PatternMatcher,而不是使用split()

    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
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2021-06-23
      • 1970-01-01
      • 2013-03-12
      相关资源
      最近更新 更多