使用 Boost 进行正则表达式标记仅获取单词的最后一个字母
我正在尝试用 Boost 解析一个简单的句子结构。这是我第一次使用 Boost,所以我可能做错了。我想要做的是只接受这种格式的字符串:
- 必须以字母开头(不区分大小写)
- 可能包含:
- 字母字符
- 数字字符
- 下划线
- 连字符
- 所有其他字符都用作分隔符
由于我不知道哪些字符是我的分隔符(可能有很多),所以我尝试制作一个对此敏感的正则表达式。唯一的问题是,我只得到每个单词的最后一个字母。这让我相信我的正则表达式是正确的,但我对 boost 的使用却不正确。这是我的代码:
boost::regex regexp("[A-Za-z]([A-Za-z]|[0-9]|_|-)*", boost::regex::normal | boost::regbase::icase);
boost::sregex_token_iterator i(text.begin(), text.end(), regexp, 1);
boost::sregex_token_iterator j;
while(i != j){
cout << *i++ << std::endl;
}
我根据在 增强网站。我使用最后一个示例(位于页面底部)作为构建 MF 代码的模板。在本例中,文本是字符串类型的对象。
我的正则表达式正确吗?我正确使用boost吗?
I am trying to parse a simple sentence structure with Boost. This is my first time using Boost, so I could be doing this completely wrong. What I want to do is only accept strings in this format:
- Must start with a letter (case insensitive)
- May contain:
- Alphabetic characters
- Numeric characters
- Underscores
- Hyphens
- All other characters serve as delimiters
Since I don't know what characters are my delimiters (there could be tons), I have tried to make a regex that is sensitive to that. The only problem is, I am only getting the last letter of each word. This leads me to believe that my regex is correct, but my use of boost is not. Here's my code:
boost::regex regexp("[A-Za-z]([A-Za-z]|[0-9]|_|-)*", boost::regex::normal | boost::regbase::icase);
boost::sregex_token_iterator i(text.begin(), text.end(), regexp, 1);
boost::sregex_token_iterator j;
while(i != j){
cout << *i++ << std::endl;
}
I modeled this after what I found on the Boost website. I used the last example (at the bottom of the page) as a template to build mf code. In this instance, text is an object of type string.
Is my regex correct? Am I using boost correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将正则表达式更改为:
([A-Za-z][-A-Za-z0-9_]*)
通过将整个表达式放在括号中,将捕获整个表达式,而不仅仅是最后一个字符匹配。将 - 放在前面会使其成为匹配字符而不是范围说明符。
Change your regex to:
([A-Za-z][-A-Za-z0-9_]*)
By putting the parentheses around the whole expression, the entire thing will be captured, not just the last character matched. Putting the - in front causes it to be a matched character and not a range specifier.
您正在请求每个 RE 匹配的第一个子匹配。它指的是这个子表达式:
([A-Za-z]|[0-9]|_|-)
并且您将得到最后一个匹配的内容(请注意,它由 < 限定) code>*) 每场比赛。因此,最后一个字符。我认为你应该为子匹配编号传递 0,或者只是省略该参数。当我修改您的代码来执行此操作时,它会执行我认为您希望它执行的操作。You're requesting the first submatch for each RE match. That refers to this subexpression:
([A-Za-z]|[0-9]|_|-)
and you're getting the last thing that matched (notice that it's qualified by a*
) for each match. Hence, the last character. I think you should pass 0 for the submatch number, or just omit that parameter. When I modify your code to do that, it does what I think you're wanting it to do.