Searching Integer value in the string

Community Alums
Not applicable

Hi Experts,

I need a java script where I should parse and get the Integer value from the string.
below are the string example,
1.Dell Latitude 1234
2.Latitude Dell 4321
3.Dell Latitude (500GB) 6789

4.Dell Latitude Longitude 5376

From the above examples the script has to pick the Integer values i.e "1234" from 1st, "4321" from 2nd, "6789" from 3rd and "5376" from 4th.. these are some different  string examples. but integer could be any where with in the string.

Kindly suggest me on this.

Thanks in advance,
Chaithanya

7 REPLIES 7

Alex Tod1
Kilo Sage

Hello @Community Alums, 

  

 // Input string
    var str = "jhkj7682834";
    gs.log(str);
 
    // Using match with regEx
    var matches = str.match(/(\d+)/);
     
    // Display output if number extracted
    if (matches) {
        gs.log(matches[0]);
    }
 
Regards,
 Alex

Community Alums
Not applicable

Hi @Alex Tod1 

Thanks for the reply, but the given script is not working the 3rd case in the above question
i.e Dell Latitude (500GB) 6789
Here script should pick 6789, but it is picking 500.

Thanks,

 

Anand Kumar P
Giga Patron
Giga Patron

Hi @Community Alums ,

I have tried in background script below script working for me.

var inputString1 = "Dell Latitude 1234";
var inputString2 = "Latitude(500) Dell";

var integers1 = inputString1.match(/\d+/g);
var integers2 = inputString2.match(/\d+/g);

var intValue1 = null;
var intValue2 = null;

if (integers1) {
  for (var i = 0; i < integers1.length; i++) {
    var tempValue = parseInt(integers1[i]);
    if (!isNaN(tempValue)) {
      intValue1 = tempValue;
      break;
    }
  }
}

if (integers2) {
  for (var i = 0; i < integers2.length; i++) {
    var tempValue = parseInt(integers2[i]);
    if (!isNaN(tempValue)) {
      intValue2 = tempValue;
      break;
    }
  }
}

gs.print(intValue1);
gs.print(intValue2); 

Please mark helpful and solution proposed if its works for you.

Thanks,

Anand

Community Alums
Not applicable

Hi @Anand Kumar P 

Thanks for the reply, but in the example "Dell Latitude (500GB) 6789" in this case script is not working. here the output should be 6789 not 500.
From this script I'm getting 500 as output

Thanks,
Chaithanya