Find second integer in String

XverhelstX

Well-Known Member
Licensed User
Longtime User
Hello,

I need to get an integer from my string.
I know it is possible with regex, etc but the problem is that I want to have the second integer instead of the first one:

Example with the following string:

Apples 1 (23 apples)

will give me 1, but i need 23.

This is the java code I use in my library:
B4X:
**
    * Finds an integer in a string.
    * @param findInt
    * @return
    */
   public String findIntegerInString(String findInt) {
      Pattern intsOnly = Pattern.compile("\\d+");
      Matcher makeMatch = intsOnly.matcher(findInt);
      makeMatch.find();
      String inputInt = makeMatch.group();
      return inputInt;
   }

but any other solution is welcome.

Thanks for any help

Tomas
 

stevel05

Expert
Licensed User
Longtime User
Hi Tomas,

If your string always contains a '(' with the number after it you can use something like:

B4X:
Sub ParseNumber(FindStr As String) As Int

   StartPos=FindStr.IndexOf("(")+1
   If StartPos <> 0 Then
      EndPos=StartPos
      Do While EndPos < FindStr.Length
         EndPos=EndPos+1
         If FindStr.CharAt(EndPos) = " " OR FindStr.CharAt(EndPos) = "." Then 'Just make sure it's an Int
            Exit
         End If
      Loop
      Num = FindStr.SubString2(StartPos,EndPos)
      If IsNumber(Num) Then Return Num
   End If
   Return -1
End Sub
 
Last edited:
Upvote 0

stevel05

Expert
Licensed User
Longtime User
No probs, you may have noticed my error :eek:

Do While StartPos < FindStr.Length

Should of course be:

Do While EndPos < FindStr.Length

It wouldn't matter unless the string is not correctly formed!
 
Upvote 0
Top