简体   繁体   中英

Fetch numeric vales from a String value in java

I want to extract numeric values from a string.

eg. I have values like this:

abc9856412368def            
9812345678abc           
abc9812345678       
abc256789def      
4567abc    

I want Output like this(in three columns):

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

If number is 10 or more than 10 then store it into col2 else in col3. I've tried using REGEXP but it doesn't extract the number in mysql workbench. But it returned zero rows.

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

I am thinking to find it using java. Stored it in resultset. I also want to make sure that mobile numbers should be inserted into Column 2. Can anyone guide me for this?

I think also in Java Regex should be the way to go.

// 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
}

Now you only need to format the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM