簡體   English   中英

解析 c++ 中的字符串,就像 python 的解析 package

[英]Parsing a string in c++ like python's parse package

在 python 中,我使用parse package 中的parse ,所以如果我有001-044.mp4 ,我可以使用模板{}-{}.mp4並將其傳遞給parse和迭代 2 個結果元素以獲得001004 在我必須根據幾個這樣的分隔符解析字符串的情況下,我想要 c++ 中的類似對應部分。 任何指針?

根據您的示例有多復雜,請考慮查看sscanfregex 兩者都不遵循 pythonic 語法,但可以用來做同樣的事情。

使用 sscanf:

#include <cstdio>

int main()
{
  const char* text = "012-231.mp4";

  int a = 0, b = 0;
  sscanf(text, "%d-%d.mp4", &a, &b);

  printf("First number: %d, second number: %d\n", a, b);
}

使用正則表達式:

#include <iostream>
#include <regex>
#include <string>

int main()
{
  std::string text = "012-231.mp4";

  std::regex expr("([0-9]*)-([0-9]*).mp4");

  std::smatch match;
  std::regex_match(text, match, expr);

  std::cout << "The matches are: ";
  // Start from i = 1; the first match is the entire string
  for (unsigned i = 1; i < match.size(); ++i) {
    std::cout << match[i] << ", ";
  }
  std::cout << std::endl;
}

如果您正在尋找行為嚴格類似於 python 格式 function 的東西,您可能必須自己編寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM