如何匹配由特定字符分隔的字符,比如“;”,并忽略匹配前后的空格,但保留匹配内部的空格?
(word1); (word2) ; (word31 word32)
Paranteses仅表示匹配。
到目前为止,我有\s*([a-zA-Z0-9\s]*[a-zA-Z0-9]+)\s*[;]
,但我不知道如何让单词重复。它还应该能够处理空词,比如(word);;(word)
、(word); ;(word)
或(word);(word);
。因为它忽略了空格,所以前两个应该是等价的。
嗯,主要的问题是,我不知道如何处理拆分和合法词和空词的两个选项,因为我的语句至少需要一个符号。
或者,如果我允许中间有空格的重复分隔符,也可以解决这个问题,但这又回到了我不知道如何处理拆分的事实上。
编辑:我还打算在C++编辑中使用它:这可能就是它,我能得到事实检查吗?\s*([a-zA-Z0-9\s]*[a-zA-Z0-9]+)[;]*\s*[;]*
发布于 2017-11-04 02:12:50
由于长正则表达式具有嵌套的量词(即使写入acc。考虑到循环展开原则)通常会导致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?。
发布于 2017-11-04 02:12:28
试试这个:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string s = " w1 w2 w3; word1 word2 ; word1 ; ";
for (std::smatch m; std::regex_search(s, m, std::regex("\\b([a-z0-9\\s]+)\\b", std::regex::icase)); s = m.suffix())
{
std::cout << m[1] << std::endl;
}
return 0;
}
打印:
w1 w2 w3
word1 word2
word1
https://stackoverflow.com/questions/47100921
复制相似问题