RegEx (3) - 使用\d 来查找所有的数字

使用python来做正则表达式:

import re 

txt = "That will be 60 dollars and the weight is 50 pounds"

#Find all digit characters:
x = re.findall("\d", txt)
print(x)

这个使用了 \ 这个character, 这个character的意思:Signals a special sequence (can also be used to escape special characters).

结果如下:
在这里插入图片描述
如果觉得不错,就点赞或者关注或者留言~~
谢谢~

regex_replace函数是C++11标准库中的一个函数,用于在字符串中查找并替换符合正则表达式的匹配项。它的定义如下: ```c++ template <class BidirIt, class Traits, class CharT, class ST> basic_string<CharT, Traits, ST> regex_replace( BidirIt first, BidirIt last, const basic_regex<CharT, Traits>& re, const basic_string<CharT, Traits, ST>& fmt, regex_constants::match_flag_type flags = regex_constants::match_default); ``` 其中,`first`和`last`表示被查找和替换的字符串范围;`re`表示正则表达式;`fmt`是替换的格式字符串;`flags`表示匹配标志,默认为`regex_constants::match_default`。 下面是一个简单的示例代码,使用正则表达式将字符串中所有数字替换为`x`: ```c++ #include <iostream> #include <regex> int main() { std::string str = "hello123world456"; std::regex re("\\d+"); std::string fmt("x"); std::string result = std::regex_replace(str, re, fmt); std::cout << result << std::endl; return 0; } ``` 输出: ``` helloxworldx ``` 在这个示例中,使用`std::regex`构造了一个正则表达式,匹配所有数字`\d+`,然后用字符串`x`替换所有匹配项。最后输出替换后的字符串。 需要注意的是,`regex_replace`函数返回的是一个新的字符串,而不是原字符串的引用。如果需要直接修改原字符串,可以使用`std::regex_replace`的另一个重载函数: ```c++ template <class Traits, class CharT, class ST, class UnaryFunction> basic_string<CharT, Traits, ST> regex_replace( const basic_string<CharT, Traits, ST>& s, const basic_regex<CharT, Traits>& re, UnaryFunction f, regex_constants::match_flag_type flags = regex_constants::match_default); ``` 其中,`f`表示替换函数,它接受一个`std::smatch`对象作为参数,返回一个替换后的字符串。这个函数可以直接修改原字符串,例如: ```c++ #include <iostream> #include <regex> int main() { std::string str = "hello123world456"; std::regex re("\\d+"); std::string result = std::regex_replace(str, re, [](const std::smatch& m) { return "x"; }); std::cout << result << std::endl; return 0; } ``` 输出: ``` helloxworldx ``` 在这个示例中,使用一个匿名Lambda函数作为替换函数,将所有匹配项替换为字符串`x`。由于是直接修改原字符串,输出结果与前面的示例相同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值