php 正则表达式:如何匹配字符串中的最后一个点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3331970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:22:10  来源:igfitidea点击:

Regex: how to match the last dot in a string

phpregex

提问by Marshall Thompson

I have two example filename strings:

我有两个示例文件名字符串:

jquery.ui.min.js
jquery.ui.min.css

What regex can I use to only match the LAST dot? I don't need anything else, just the final dot.

我可以使用什么正则表达式来只匹配最后一个点?我不需要其他任何东西,只需要最后一个点。

A little more on what I'm doing. I'm using PHP's preg_split() function to split the filename into an array. The function deletes any matches and gives you an array with the elements between splits. I'm trying to get it to split jquery.ui.min.js into an array that looks like this:

多一点关于我在做什么。我正在使用 PHP 的 preg_split() 函数将文件名拆分为一个数组。该函数删除任何匹配项,并为您提供一个包含拆分之间元素的数组。我试图让它将 jquery.ui.min.js 拆分成一个如下所示的数组:

array[0] = jquery.ui.min
array[1] = js

采纳答案by deceze

I think you'll have a hard time using preg_split, preg_matchshould be the better choice.

我想你会很难使用preg_splitpreg_match应该是更好的选择。

preg_match('/(.*)\.([^.]*)$/', $filename, $matches);

Alternatively, have a look at pathinfo.
Or, do it very simply in two lines:

或者,看看pathinfo
或者,只需两行即可:

$filename = substr($file, 0, strrpos($file, '.'));
$extension = substr($file, strrpos($file, '.') + 1);

回答by paxdiablo

If you're looking to extract the last part of the string, you'd need:

如果您想提取字符串的最后一部分,则需要:

\.([^.]*)$

if you don't want the .or

如果你不想要.

(\.[^.]*)$

if you do.

如果你这样做。

回答by Crayon Violent

At face value there is no reason to use regex for this. Here are 2 different methods that use functions optimized for static string parsing:

从表面上看,没有理由为此使用正则表达式。以下是使用为静态字符串解析优化的函数的 2 种不同方法:

Option 1:

选项1:

$ext = "jquery.ui.min.css";
$ext = array_pop(explode('.',$ext));
echo $ext;

Option 2:

选项 2:

$ext = "jquery.ui.min.css";
$ext = pathinfo($ext);
echo $ext['extension'];

回答by Brandon Horsley

\.[^.]*$

回答by Jaans

Here's what I needed to exclude the last dotwhen matching for just the last "part":

这是我在匹配最后一个“部分”时排除最后一个点所需的内容:

[^\.]([^.]*)$

回答by someguy

I used this - give it a try:

我用过这个 - 试试看:

m/\.([^.\]+)$/