Home > Enterprise >  How to read number from given text in java
How to read number from given text in java

Time:01-24

I am trying to read otp number from given String i have applied this below string but i am getting two number can any one please help me how to get otp number

String str="Your OTP for Darshann is : 9999%n 12341234123";
String numberOnly= str.replaceAll("[^0-9]", "");

I want to read number just after Your OTP for Darshann is : this text which is 9999 i

CodePudding user response:

By replacing with empty string "" you are concatenating the numbers. This is why have incorrect results. Try this instead:

String str="Your OTP for Darshann is : 9999%n 12341234123";
    
String numberOnly= str.replaceAll("[^0-9]", " ");
List<String> numbers = Arrays.asList(numberOnly.trim().split(" ")).stream()
        .filter(s->!s.isBlank())
        .collect(Collectors.toList());
System.out.println(numbers);

This would give a list of all numbers found in the text:

[9999, 12341234123]

Of course if there is more than one number in the string this function will produce more than one result.

CodePudding user response:

String message = "Your OTP for Darshann is 1234";

// split the message by "is"
String[] parts = message.split("is ");


String OTP = parts[1];

// rgx
Pattern pattern = Pattern.compile("\\d ");
Matcher matcher = pattern.matcher(OTP);

if (matcher.find()) {
    String OTPnumber = matcher.group();
    System.out.print("OTP is: "   OTPnumber);
} else {
    System.out.println("not found");
}
  •  Tags:  
  • java
  • Related