简体   繁体   English

用于删除后缀的正则表达式

[英]Regular Expression for removing suffix

What is the regular expression for removing the suffix of file names? 删除文件名后缀的正则表达式是什么? For example, if I have a file name in a string such as "vnb.txt", what is the regular expression to remove ".txt"? 例如,如果我在诸如“ vnb.txt”的字符串中有一个文件名,那么删除“ .txt”的正则表达式是什么? Thanks. 谢谢。

Do you really need a regular expression to do this? 您真的需要一个正则表达式来做到这一点吗? Why not just look for the last period in the string, and trim the string up to that point? 为什么不只寻找字符串的最后一个句点,并修剪字符串到该点呢? Frankly, there's a lot of overhead for a regular expression, and I don't think you need it in this case. 坦白说,正则表达式有很多开销,在这种情况下,我认为您不需要它。

As suggested by tstenner, you can try one of the following, depending on what kinds of strings you're using: 如tstenner所建议,您可以尝试以下一种方法,具体取决于您使用的是哪种字符串:

std::strrchr std :: strrchr

std::string::find_last_of std :: string :: find_last_of

First example: 第一个例子:

char* str = "Directory/file.txt";

size_t index;
char* pStr = strrchr(str,'.');
if(nullptr != pStr)
{
    index = pStr - str;
}

Second example: 第二个例子:

int index = string("Directory/file.txt").find_last_of('.');

If you're looking for a solution that will give you anything except for the suffix, you should use string::find_last_of . 如果您正在寻找一个可以提供除后缀之外的任何内容的解决方案,则应使用string :: find_last_of

Your code could look like this: 您的代码可能如下所示:


const std::string removesuffix(const std::string& s) {
  size_t suffixbegin = s.find_last_of('.');

  //This will handle cases like "directory.foo/bar"
  size_t dir = s.find_last_of('/');
  if(dir != std::string::npos && dir > suffixbegin) return s;
  if(suffixbegin == std::string::npos) return s;
  else return s.substr(0,suffixbegin);
}

If you're looking for a regular expression, use \\.[^.]+$ . 如果要查找正则表达式,请使用\\.[^.]+$
You have to escape the first . 您必须先逃避. , otherwise it will match any character, and put a $ at the end, so it will only match at the end of a string. ,否则它将匹配任何字符,并将$放在末尾,因此它将仅匹配字符串的末尾。

如果已经使用Qt,则可以使用QFileInfo ,并使用baseName()函数仅获取名称(如果存在),或使用suffix()函数获取扩展名(如果存在)。

Different operating systems may allow different characters in filenams, the simplest regex might be (.+)\\.txt$ . 不同的操作系统可能在文件名中允许使用不同的字符,最简单的正则表达式可能是(.+)\\.txt$ Get the first capture group to get the filename sans extension. 获取第一个捕获组以获取没有扩展名的文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM