首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >匹配由符号分隔的重复单词并忽略空格

匹配由符号分隔的重复单词并忽略空格
EN

Stack Overflow用户
提问于 2017-11-04 00:59:36
回答 2查看 59关注 0票数 0

如何匹配由特定字符分隔的字符,比如“;”,并忽略匹配前后的空格,但保留匹配内部的空格?

(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*[;]*

EN

回答 2

Stack Overflow用户

发布于 2017-11-04 02:12:50

由于长正则表达式具有嵌套的量词(即使写入acc。考虑到循环展开原则)通常会导致std::regex出现问题,在这种情况下,似乎拆分方法是最好的。

这是一个C++ demo

代码语言:javascript
运行
复制
#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;
}

输出:

代码语言:javascript
运行
复制
'word1'
'word2'
'word31 word32'

该模式是在R"(\s*;\s*)"中定义的-它匹配用0+空格括起来的分号。

注意:这种方法可能需要从空格中裁剪输入字符串,有关剥离前导/尾随空格的各种方法,请参阅What's the best way to trim std::string?

票数 1
EN

Stack Overflow用户

发布于 2017-11-04 02:12:28

试试这个:

代码语言:javascript
运行
复制
#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;
}

打印:

代码语言:javascript
运行
复制
w1 w2 w3
word1 word2
word1
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47100921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档