为什么正则表达式在C++的日语字符串中找不到“(”

Why can't regex find the "(" in a Japanese string in C++?

本文关键字:找不到 字符串 日语 正则表达式 C++ 为什么      更新时间:2023-10-16

我有一大堆日语例句。它的设置是一行是句子,然后下一行由句子中使用的单词组成,由 {}、() 和 [] 分隔。基本上,我想从文件中读取一行,只找到 () 中的单词,将它们存储在单独的文件中,然后从字符串中删除它们。

我正在尝试使用正则表达式执行此操作。这是我正在使用的文本:

は 二十歳(はたち){20歳} になる[01]{になりました}

这是我用来查找()之间的内容的代码:

std::smatch m;
std::regex e ("(([^)]+))");   // matches things between ( and )
if (std::regex_search (components,m,e)) {
   printToTest(m[0].str(), "what we got"); //Prints to a test file "what we got: " << m[0].str()
   components = m.prefix().str().append(m.suffix().str());
   //commponents is a string
   printToTest(components, "[COMP_AFTER_REMOVAL]");
   //Prints to test file "[COMP_AFTER_REMOVAL]: " << components 
}

以下是应该打印的内容:

what we got:はたち
[COMP_AFTER_REMOVAL]:は 二十歳(){20歳} になる[01]{になりました}

以下是打印的内容:

what we got:は 二十歳(はたち
[COMP_AFTER_REMOVAL]:){20歳} になる[01]{になりました}

似乎不知何故将 は 混淆为 a (,这使得正则表达式从 は 变为 )。我相信这是从文件中读入行的方式有问题。也许它没有以某种方式被读为 utf8。这是我的工作:

xml_document finalDoc;
string sentence;
string components;
ifstream infile;
infile.open("examples.utf");
unsigned int line = 0;
string linePos;
bool eof = infile.eof();
while (!eof && line < 1){       
    getline(infile, sentence);
    getline(infile, components);
    MakeSentences(sentence, components, finalDoc);
    line++;
}

有什么不对吗?有什么提示吗?需要更多代码?请帮忙。谢谢。

你忘了转义反斜杠。编译器看到"(([^)]+))"并将其解释为(([^)]+))这不是您想要的正则表达式。

您需要键入"\(([^)]+)\)"