如何匹配由特定字符分隔的字符,比方说 ';'并忽略比赛前后的空间,但保留里面的空间?
(word1); (word2) ; (word31 word32)
Paranteses 只表示匹配。
到目前为止,我有 \s*([a-zA-Z0-9\s]*[a-zA-Z0-9]+)\s*[;]
但我没有'知道如何使单词重复。而且它还应该能够处理空词,比如 (word);;(word)
,(word); ;(word)
或 (word);(word);
。由于它忽略了空格,因此前两个应该是等价的。
主要问题是我不知道如何处理拆分以及合法词和空词这两个选项,因为我的语句至少需要 1 个符号。
或者,如果我允许中间有空格的重复分隔符,则可以解决此问题,但这又回到了我不知道如何处理拆分的事实。
编辑:我还打算在 C++ 中使用它
编辑:这可能是它,我可以得到事实核查吗? \s*([a-zA-Z0-9\s]*[a-zA-Z0-9]+)[;]*\s*[;]*
最佳答案
由于带有嵌套量词的长正则表达式(即使根据展开循环原则编写)通常会导致 std::regex
出现问题,因此拆分方法似乎是最好的方法情况。
这是一个C++ demo :
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::vector<std::string> strings;
std::string s = "word1; word2 ; word31 word32";
std::regex re(R"(\s*;\s*)");
std::regex_token_iterator<std::string::iterator> it(s.begin(), s.end(), re, -1);
decltype(it) end{};
while (it != end){
strings.push_back(*it++);
}
for (auto& s: strings){ //std::cout << strings[strings.size()-1] << std::endl;
std::cout << "'" << s << "'" << std::endl;
}
return 0;
}
输出:
'word1'
'word2'
'word31 word32'
该模式在 R"(\s*;\s*)"
中定义 - 它匹配用 0+ 个空格括起来的分号。
注意:此方法可能需要从空格中删除输入字符串,请参阅 What's the best way to trim std::string?用于剥离前导/尾随空格的各种方法。
关于c++ - 匹配由符号分隔并忽略空格的重复单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100921/