Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

php - Regular Expression to collect everything after the last /

I'm new at regular expressions and wonder how to phrase one that collects everything after the last /.

I'm extracting an ID used by Google's GData.

my example string is

http://spreadsheets.google.com/feeds/spreadsheets/p1f3JYcCu_cb0i0JYuCu123

Where the ID is: p1f3JYcCu_cb0i0JYuCu123

Oh and I'm using PHP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This matches at least one of (anything not a slash) followed by end of the string:

[^/]+$


Notes:

  • No parens because it doesn't need any groups - result goes into group 0 (the match itself).
  • Uses + (instead of *) so that if the last character is a slash it fails to match (rather than matching empty string).


But, most likely a faster and simpler solution is to use your language's built-in string list processing functionality - i.e. ListLast( Text , '/' ) or equivalent function.

For PHP, the closest function is strrchr which works like this:

strrchr( Text , '/' )

This includes the slash in the results - as per Teddy's comment below, you can remove the slash with substr:

substr( strrchr( Text, '/' ), 1 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...