0

I am trying to extract the integers from a string.

String :

Str = "(Start = 10) AND (End_ = 40)"

Note: The integers here can range from 1 - 999, single digit to three digits

Desired Output:

No1 = 10
No2 = 40
4
  • Please show your attempt(s). What isn't working in your code? Commented Nov 28, 2018 at 1:08
  • Thank you for your quick response. Here is my attempt: var clause = "(Start = 231) AND (End_ = 24)"; var s_node,e_node, cnt=0; for(i=0; i< clause.length; i++){ var a = parseInt(clause[i]); if(Number.isInteger(a)) { if(cnt == 0){ s_node = a; cnt++ } else{ e_node = a; } } } console.log(s_node, e_node) This works if I have single digit integer within a string. Works if, var clause = "(Start = 1) AND (End_ = 4)" fails if, var clause = "(Start = 231) AND (End_ = 24)" Commented Nov 28, 2018 at 1:15
  • 00[1-9]|0[1-9]\d|[1-9]\d{2} Commented Nov 28, 2018 at 1:27
  • Note that 1-3 digits are not enough to describe the problem, since 20455 will also match. You'd need to add a boundary condition or two. Commented Nov 28, 2018 at 1:34

1 Answer 1

2

This code will get you what you want, an array of numbers found in the string.

Explanation

The regular expression looks for a single number 1 through 9 [1-9] followed by 0, 1, or 2 {0,2} numbers between 0 through 9 [0-9]. The g means global, which instructs match() to check the entire string and not stop at the first match.

Code

var str = "(Start = 10) AND (End_ = 40)";
var numbers = str.match(/[1-9][0-9]{0,2}/g);

console.log(numbers);

Sign up to request clarification or add additional context in comments.

7 Comments

Updated the regular expression to NOT capture 0, or any number prefixed by 0.
There wont be "0" in the main string however, I can make the changes accordingly.
single digit to three digits so can it start with 0 like 001 ?
@sln, No it will not have 0. eg: 1,2,3,.......,11,12,.......,111,...,999
Cool, then the updated regex will work perfectly for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.