简体   繁体   中英

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"? 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:

std::strrchr

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 .

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$ . Get the first capture group to get the filename sans extension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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