Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match number at the end of the string

Tags:

regex

php

Given the following string how can I match the entire number at the end of it?

$string = "Conacu P PPL Europe/Bucharest 680979";

I have to tell that the lenght of the string is not constant.

My language of choice is PHP.

Thanks.

like image 202
Psyche Avatar asked Sep 20 '09 12:09

Psyche


People also ask

How do you find the number at the end of a string?

To get the number from the end of a string, call the match() method, passing it the following regular expression [0-9]+$ . The match method will return an array containing the number from the end of the string at index 0 .

What matches the end of the string?

End of String or Before Ending Newline: \Z. The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string.

Which matches the start and end of the string?

Explanation: '^' (carat) matches the start of the string. '$' (dollar sign) matches the end of the string. Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.

What matches the start of the string?

They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.


2 Answers

You could use a regex with preg_match, like this :

$string = "Conacu P PPL Europe/Bucharest 680979";

$matches = array();
if (preg_match('#(\d+)$#', $string, $matches)) {
    var_dump($matches[1]);
}

And you'll get :

string '680979' (length=6)

And here is some information:

  • The # at the beginning and the end of the regex are the delimiters -- they don't mean anything : they just indicate the beginning and end of the regex ; and you could use whatever character you want (people often use / )
  • The '$' at the end of the pattern means "end of the string"
  • the () means you want to capture what is between them
    • with preg_match, the array given as third parameter will contain those captured data
    • the first item in that array will be the whole matched string
    • and the next ones will contain each data matched in a set of ()
  • the \d means "a number"
  • and the + means one or more time

So :

  • match one or more number
  • at the end of the string

For more information, you can take a look at PCRE Patterns and Pattern Syntax.

like image 194
Pascal MARTIN Avatar answered Nov 15 '22 14:11

Pascal MARTIN


The following regex should do the trick:

/(\d+)$/
like image 20
Jani Hartikainen Avatar answered Nov 15 '22 14:11

Jani Hartikainen