从评论中提取版本号[关闭]

I have a CSS (or HTML or JS) file with a comment /* Version: 1.2.1 */ near the beginning of the file.

Using PHP/regex, how do I get a string containing '1.2.1'?

I apologise for not RTFM but I can't find an answer on the Google. Any direction on learning regex would be great!

$str = '/* Version 1.2.1 */';
preg_match('/version\s(.*)\s\*/i',$str,$matches);

print_r($matches[1]);

its very simple to grap, \s(.*)\s capture anything in between spaces as first group. display first captured group $matches[1]

if you are curious that how it works or wanna learn yourself ? you can dive directly into it from here i found this very helpful for beginner.

Regular Expressions!

DIY

To begin with regex learning, I strongly recommend these two sites:

To test your regex regex101 is particularly usefull.


That being said, you have two options to consider:

  1. You want to work with a capture group.
  2. You want to get only a match.

If you can work with a capture group, simple regex will work:

^\s*\/\* Version: (\d\.\d\.\d) \*\/

This will capture the version number in group 1 (demo).

When you want to only get the matching version number but don't want to bother with a capture group, you have to work with lookarounds:

  • A lookbehind allows you to check for text preceding the match. In your case: (?<=\/\* Version: ).
  • A lookafter to check for the comment end: (?= \/\*).

Assembled with version number matching (demo):

(?<=\/\* Version: )\d\.\d\.\d(?= \*\/)