This tutorial will show you how we can extract the first non-breakable numeric values from a string using Java.

Create below method in Java class to extract numeric value

public static String getFirstContinousNumericFromString(String string) {
    Pattern pattern = Pattern.compile("(\\d+\\.+\\d+)|(\\d+)");
    Matcher matcher = pattern.matcher(string);
    matcher.find();
    return matcher.group();
}


The whole class

package com.roytuts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractNumericValues {

  /**
   * @param args
   */
  public static void main(String[] args) {
    String number1 = getFirstContinousNumericFromString("AB: [C D] 4110007.325");
    System.out.println("number1 : " + number1);
    String number2 = getFirstContinousNumericFromString("209ca56b-deea-4874-81d6-e9cdaa74a7c7");
    System.out.println("number2 : " + number2);
    String number3 = getFirstContinousNumericFromString("AB: [C D] 4110007.325 1253");
    System.out.println("number3 : " + number3);
    String number4 = getFirstContinousNumericFromString("ca56b-deea-4874-81d6-e9cdaa74a7c7");
    System.out.println("number4 : " + number4);
  }

  public static String getFirstContinousNumericFromString(String string) {
    Pattern pattern = Pattern.compile("(\\d+\\.+\\d+)|(\\d+)");
    Matcher matcher = pattern.matcher(string);
    matcher.find();
    return matcher.group();
  }

}

Run the above class, you will get the below results

number1 : 4110007.325
number2 : 209
number3 : 4110007.325
number4 : 56

Thanks for the reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *