如何使用正则表达式从 CString 中提取名称?

编程入门 行业动态 更新时间:2024-10-09 23:13:27
本文介绍了如何使用正则表达式从 CString 中提取名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

采用具有以下定义的 CString:

Take a CString that has the following definition:

CString strNameText = _T("Mr Happy [12]");

我有一系列的名字,所有的名字都有空格,最后是括号.现在我只想从字符串中提取名称.

I have a series of names with all have the space with a number is brackets at the end. Now I want to extract just the name from the string.

我意识到我可以找到"的第一个索引[" 然后提取左侧的文本直到该索引.但是我可以使用任何正则表达式命令来做同样的事情吗?

I realise that I can find the first index of " [" and then extract the text on the left up to that index. But can I use any regex command to do the same?

推荐答案

我可能会建议在此处替换正则表达式,以删除字符串末尾的括号术语.

I might suggest a regex replacement here, to remove the bracketed term at the end of the string.

std::string strNameText ("Mr Happy [12]");
std::regex r ("\\s+\\[\\d+\\]$");
std::cout << std::regex_replace (strNameText, r, "");  // Mr Happy


C++ 示例

#include <regex>

CString strNameText = _T("Mr Happy [12]");

std::string s1 = CT2A(strNameText);
std::regex r("\\s+\\[\\d+\\]$");
std::string s2 = std::regex_replace(s1, r, "");

return CString(s2.c_str());

这篇关于如何使用正则表达式从 CString 中提取名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 15:21:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   名称   正则表达式   CString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!