explorers' club

explorations in dev, science, sci-fi, games, and other fun stuff!

Regexp: extract numbers from end of string

1 Comment

[note to self]

task:

For a given string that contains one or more grouping of digits, extract the last grouping of digits.

desired result:

var s:String = "blah blah 123 blah 456 today is Blah 24 2011";
var desiredOutput:String = "2011";

solution:

var s:String = "custom label 24";
var i:int = s.search( /(\d)+$/ );	
var output:String = s.substring( i ); 
trace( output ); //"24"

regexp explanation:

Given the following regexp:

/(\d)+$/
  • (\d) – digits grouping
  • + – greedy match, meaning try to group as many digits as possible before satisfying the group matching
  • $ – start at the end of the string

Notice I did not use the global flag g at the end of the regexp.

Advertisements

One thought on “Regexp: extract numbers from end of string

  1. I have an interesting one…
    Given a string s= “lala12la23”;
    Can you extract the number (23) from the end of the string, and at the same time extract the preceding text?

    Can it be done with 1 regex containing 2 groups?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s