提高正则表达式提取字符串中的数字 [英] boost regex to extract a number from string

查看:129
本文介绍了提高正则表达式提取字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串
资源=/音乐/ 1
后面的字符串可以采取多个数值/音乐/。我新的定期EX pression东西。我尝试以下code

I have a string resource = "/Music/1" the string can take multiple numeric values after "/Music/" . I new to regular expression stuff . I tried following code

#include <iostream>

#include<boost/regex.hpp>

int main()
{
    std::string resource = "/Music/123";

    const char * pattern = "\\d+";

    boost::regex re(pattern);

    boost::sregex_iterator it(resource.begin(), resource.end(), re);
    boost::sregex_iterator end;

    for( ; it != end; ++it)
    {
        std::cout<< it->str() <<"\n";
    }
    return 0;
}

vickey@tb:~/trash/boost$ g++ idExtraction.cpp  -lboost_regex
vickey@tb:~/trash/boost$ ./a.out 
123

正常工作。但是,即使当字符串恰好是类似/ Music23 / 123它给我一个价值23 123前,当我使用的模式/ \\ D +的时候,串/ 23 /音乐/ 123它将给结果事件。我想要做的是后/音乐/提取的唯一编号。

works fine . But even when the string happens to be something like "/Music23/123" it give me a value 23 before 123. When I use the pattern "/\d+" it would give results event when the string is /23/Music/123. What I want to do is extract the only number after "/Music/" .

推荐答案

我认为问题的一部分是,你还没有定义得很好(至少对我们)什么是你试图匹配。我会采取一些猜测。也许人会满足您的需求。

I think part of the problem is that you haven't defined very well (at least to us) what it is you are trying to match. I'm going to take some guesses. Perhaps one will meet your needs.


  • 在您输入字符串结尾的数字。例如,/ A / B / 34 。使用表达式\\\\ D + $

  • 这完全是数字的路径元素。例如,/ A / B / 12 / c或/ A / B / 34 而不是/ A / B56 / D。使用表达式(?:^ | /)(\\\\ D +)(?:/ | $)并获得捕获组[1]。你可能会做同样的事情与前瞻和回顾后,或许与(小于?= ^ | /)\\\\ D +(?= / | $)。

  • The number at the end of your input string. For example "/a/b/34". Use regex "\\d+$".
  • A path element that is entirely numeric. For example "/a/b/12/c" or "/a/b/34" but not "/a/b56/d". Use regex "(?:^|/)(\\d+)(?:/|$)" and get captured group [1]. You might do the same thing with lookahead and lookbehind, perhaps with "(?<=^|/)\\d+(?=/|$)".

这篇关于提高正则表达式提取字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆