【问题标题】:Fetch numeric vales from a String value in java从java中的String值中获取数值
【发布时间】:2016-12-26 04:35:19
【问题描述】:

我想从字符串中提取数值。

例如。我有这样的价值观:

abc9856412368def            
9812345678abc           
abc9812345678       
abc256789def      
4567abc    

我想要这样的输出(三列):

Col1         Col2            Col3
abc def    9856412368
abc        9812345678 
abc        9812345678
abc def                     256789
abc                         4567

如果数字是 10 或大于 10,则将其存储到 col2 中,否则存储在 col3 中。我试过使用 REGEXP 但它没有提取 mysql 工作台中的数字。但它返回零行。

select first_name
from mytable
where First_Name regexp '^[0-9]+$' and First_Name!=""

我想用java找到它。将其存储在结果集中。我还想确保将手机号码插入第 2 列。有人可以指导我吗?

【问题讨论】:

    标签: java mysql sql resultset


    【解决方案1】:

    我认为 Java Regex 也应该是要走的路。

    // Extract numbers from String
    Pattern p1 = Pattern.compile("-?\\d+");
    // Extract words from String
    Pattern p2 = Pattern.compile("-?\\D+");
    
    Matcher m1 = p1.matcher("abc9856412368def");
    Matcher m2 = p2.matcher("abc9856412368def");
    while (m1.find()) {
      System.out.println(m.group()); // Prints 9856412368
    }
    while (m2.find()) {
      System.out.println(m.group()); // Prints abc and def
    }
    

    现在你只需要格式化输出。

    【讨论】:

    • 感谢您的帮助。但是我有一个庞大的数据,字符串中的数字可以在任何地方。我需要从整个字符串中获取这些数字。并将它们插入到另一列中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多