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.
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 .
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.
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.
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”.
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:
#
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 /
)()
means you want to capture what is between them
preg_match
, the array given as third parameter will contain those captured data()
\d
means "a number"+
means one or more timeSo :
For more information, you can take a look at PCRE Patterns and Pattern Syntax
.
The following regex should do the trick:
/(\d+)$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With