QT 正则表达式 通常用法
来源:互联网 发布:java一般怎么调试文件 编辑:程序博客网 时间:2024/05/21 09:17
转自:http://hi.baidu.com/kxw102/item/df64ea3ef228f8fadf22213e
Qt里对大名鼎鼎的正则表达式有很好的支持,使用QRegExp类,你可以非常快的完成对文本的验证、数据提取、替换。Qt的SDK包里还提供了regexp的GUI小工具,方便你对正则表达式的验证。
本文在Qt4.5.3下验证通过。
用正则表达式验证文本有效性你可以使用QRegExp::exactMatch来判断一个字符串是否符合一个pattern。
void testRegexMatch(){
QString pattern(".*=.*");
QRegExp rx(pattern);
bool match = rx.exactMatch("a=3");
qDebug() << match; // True
match = rx.exactMatch("a/2");
qDebug() << match; // False
}
用正则表达式提取数据
你可以利用利用正则表达式从一个字符串里提取特定的字段或数据。例如,你可以用以下代码从"a=100"里提取"a"和"100"。
void testRegexCapture(){
QString pattern("(.*)=(.*)");
QRegExp rx(pattern);
QString str("a=100");
int pos = str.indexOf(rx); // 0, position of the first match.
// Returns -1 if str is not found.
// You can also use rx.indexIn(str);
qDebug() << pos;
if ( pos >= 0 )
{
qDebug() << rx.matchedLength(); // 5, length of the last matched string
// or -1 if there was no match
qDebug() << rx.capturedTexts(); // QStringList("a=100", "a", "100"),
// 0: text matching pattern
// 1: text captured by the 1st ()
// 2: text captured by the 2nd ()
qDebug() << rx.cap(0); // a=100, text matching pattern
qDebug() << rx.cap(1); // a, text captured by the nth ()
qDebug() << rx.cap(2); // 100,
qDebug() << rx.pos(0); // 0, position of the nth captured text
qDebug() << rx.pos(1); // 0
qDebug() << rx.pos(2); // 2
}
}用正则表达式修改文本
你可以把字符串中匹配的字符串替换成"一般字符串"
QString s = "a=100";s.replace(QRegExp("(.*)="), "b=");
qDebug() << s; // b=100
或是把字符串中匹配的字符串替换"提取的字符串"
QString s = "a=100";s.replace(QRegExp("(.*)=(.*)"), "\\1\\2=\\2"); // \1 is rx.cap(1), \2 is rx.cap(2)
qDebug() << s; // a100=100把正则表达式转换成C/C++ string的小工具
没有Python的"""或是C#的@。标准的正则表达式因为出现一些特殊字符,在C/C++代码里使用时,必须进行转换。例如:"(\S+)\s*=\s*(\S*)"必须转换成"(\\S+)\\s*=\\s*(\\S*)"
Qt的SDK里包含一个很帮的GUI工具,可以方便我们进行这类转换并测试你的表达式。在Linux下,它的路径是/usr/local/Trolltech/Qt-4.5.3/examples/tools/regexp/regexp- QT 正则表达式 通常用法
- QT 正则表达式 通常用法
- QT的正则表达式用法
- Qt正则表达式
- QT的正则表达式
- Qt中的正则表达式
- QT之正则表达式
- QT的正则表达式
- QT中的正则表达式
- QT的正则表达式
- Qt正则表达式
- qt 正则表达式
- Qt 正则表达式
- Qt之正则表达式
- qt之正则表达式
- Qt 正则表达式 例子
- Qt正则表达式
- Qt正则表达式
- 史上自定义 JavaScript 函数Top 10
- 用TextView实现Rich Text---在同一个TextView中设置不同的字体风格
- MyBatis整理
- objc_msgSend函数 iphone
- UIWebView网页视图
- QT 正则表达式 通常用法
- Qt4--创建自定义图标
- 博弈论入门导论
- Rails 调试
- wait、sleep、interrupt、notify
- 深入理解Java中的多线程
- 【自动回帖器/原理】自动回帖器的原理与实现(二)代码篇
- 孙鑫VC++深入详解:Lesson1
- 判别模型和生成模型