Jump to content


Photo

Regex to Pull just the number


  • Please log in to reply
2 replies to this topic

#1 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 258 posts
  • LocationSalisbury

Posted 08 November 2017 - 04:14 PM

I suck at regex! i need to pull just the number after "[License Number:" and between "-Expiration Date:11/19/2018-State Issued:CA]" in the below, how would I do that. 

[License Number:AG013440-Expiration Date:11/19/2018-State Issued:CA]

 

Thanks in advance



#2 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 258 posts
  • LocationSalisbury

Posted 08 November 2017 - 04:49 PM

i got it

 $matches = array();
 preg_match('/:(.*?)\-/s', $license, $matches);
 $license =  $matches[1];


#3 Psycho

Psycho
  • Moderators
  • Move along, nothing to see here
  • 11,847 posts
  • LocationCanada

Posted 08 November 2017 - 06:57 PM

Hmm, pretty sure that is an inefficient RegEx. It is using the greedy '*' along with the lazy modifier '?'. That causes the matching to do some recursive logic to get the result.

 

I think a better solution would be this

/License Number:([^-]*)/s

 

This is a strait-forward, efficient matching that will pull every character following 'License Number:' up to, but not including, the '-' character. Yes, you could just put a colon instead of the full 'License Number:' string, but it will be patently obvious to anyone else reading the code (or even to you if you have to go back to it in a few months).


The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users