Qt学习:正则表达式 - QRegExp

来源:互联网 发布:java继承笔记 编辑:程序博客网 时间:2024/05/16 01:11
用正则表达式验证文本有效性
你可以使用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}


QLineEdit 限制整数

m_LineEditIterate = new QLineEdit();  m_LineEditIterate->setFixedWidth(100);  m_LineEditIterate->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);  m_LineEditIterate->setText("2");  m_LineEditIterate->setValidator(new QIntValidator(1, 9, m_LineEditIterate)); 

QLieEdit限制double类型,以及小数点,{0,2}这个是控制位数,

QRegExp double_rx100("100([0-9]{0,2}[\.][0-9]{1,3})");   QRegExp double_rx10("10([0-9]{0,4}[\.][0-9]{1,3})");   QRegExp double_rx10("10([0-9]{0,1}[\.][0-9]{1,3})");   m_LineEditDensity = new QLineEdit;  m_LineEditDensity->setValidator(new QRegExpValidator(double_rx100, m_LineEditDensity));  m_LineEditParA = new QLineEdit;  m_LineEditParA->setValidator(new QRegExpValidator(double_rx10, m_LineEditParA));  m_LineEditParB = new QLineEdit;  m_LineEditParB->setValidator(new QRegExpValidator(double_rx10, m_LineEditParB)); 

QLineEdit只输入字母和数字

QRegExp regx("[a-zA-Z0-9]+$");  QValidator *validator = new QRegExpValidator(regx, lined );  lined->setValidator( validator );


用正则表达式提取数据

你可以利用利用正则表达式从一个字符串里提取特定的字段或数据。例如,你可以用以下代码从"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    }}</span>

用正则表达式修改文本

你可以把字符串中匹配的字符串替换成"一般字符串"

QString s = "a=100";    s.replace(QRegExp("(.*)="), "b=");    qDebug() << s;                          // b=100

或是把字符串中匹配的字符串替换"提取的字符串"

QString s = "a=100";s.replace(QRegExp("(.*)=(.*)"), "\\1\\2=\\2");qDebug() << s;                                 

还可以控制输入文本的格式

// ## 设置身份证和联系电话只能输入数字    QRegExp regx("[0-9]+$");    QValidator * validator = new QRegExpValidator(regx, ui->cidLineEdit);    ui->cidLineEdit->setValidator(validator);    ui->cphoneLineEdit->setValidator(validator);

QRegExp::QRegExp ( const QRegExp & rx )//建立一个正则表达式,该表达式是rx的复制版

如程序中建立的匹配节点重启的正则表达式QRegExp  regexp("TaskCTLL");就是以TaskCTLL为表达式进行匹配。

QRegExp::QRegExp ( const QString & pattern, Qt::CaseSensitivity cs = Qt::CaseSensitive, PatternSyntax syntax = RegExp )//根据给定的模式串(pattern string)建立正则表达式对象,模式串必须以通配符(wildcard)的形式给出

如程序中建立的匹配第一父节点的正则表达式QRegExp  regexpparent("parent\\[0\\]\\s+\\-{0,1}(\\d+)\\b");

int QRegExp::indexIn ( const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero ) const//企图从位置偏移为零(默认值)出找到一个匹配的字符处str,返回第一个匹配点的位置position,如果没有匹配则返回-1

程序中只需要匹配一次(文本文件中每一行只有一个不重复的str),只要匹配成功返回值不是-1,就对信息进行提取保存

Qt里的正则表达式和C++里面的有些差别,例如\\.表示.   \\d表示d

程序实例:
匹配时钟跳变   
2011/06/27 22:05:42.011    parent[1]  -1
2011/06/27 22:05:42.011    Local time  2d5820d
":(\\d+)\\.(\\d+)\\s+(\\w*\\s*\\w*\\s*\\d*\\,\\s*)*(\\w*\\s*)*(parent\\[[01]\\]\\s+\\-{0,1}\\d+)*(\\w*\\d*\\.\\d*\\w*\\s*\\d*)*Local\\s+time"

匹配第一父节点
2011/06/27 22:05:42.011    parent[0]  6003
"parent\\[0\\]\\s+\\-{0,1}(\\d+)\\b"

匹配节点号
2011/06/27 22:26:30.090    mac neigh 0,  addr 100
"mac\\s+neigh\\s+0\\,\\s+addr\\s+(\\d+)\\b"

根节点收到数据
2011/06/27 22:07:45.058    ROOT receive data origin 52 100
"ROOT\\s+receive\\s+\\dada\\s+\\origin\\s+(\\d+)\\s+(\\d+)\\b"

 
常用正则表达式
表达式说明\r, \n代表回车和换行符\t制表符\\代表 "\" 本身\^匹配 ^ 符号本身\$匹配 $ 符号本身元字符说明.匹配除了换行符以外的任意字符\w匹配字母、数字、下划线、汉字\s匹配任意的空白符\b单词的开始或结尾\~匹配字符串的开始$匹配字符串的结束

如:

\ba\w*\b :匹配以字母a开头的单词——先是某个单词开始处(\b),然后是字母a,然后是任意数量的字母或数字(\w*),最后是单词结束处(\b)。

\d+ :匹配1个或更多连续的数字。这里的+是和*类似的元字符,不同的是*匹配重复任意次(可能是0次),而+则匹配重复1次或更多次。

\b\w{6}\b: 匹配刚好6个字符的单词。

表达式说明[ ]包含一系列字符[^ ]包含之外一系列字符

[ab5@]: 匹配 "a" 或 "b" 或 "5" 或 "@"

[^abc]: 包含abc之外的任意字符

[f-k]: f-k之间的任意字符

表达式说明{n}表达式重复n次,比如:"\w{2}" 相当于 "\w\w";"a{5}" 相当于 "aaaaa"{m,n}表达式至少重复m次,最多重复n次,比如:"ba{1,3}"可以匹配 "ba"或"baa"或"baaa{m,}表达式至少重复m次,比如:"\w\d{2,}"可以匹配 "a12","_456","M12344"...?匹配表达式0次或者1次,相当于 {0,1},比如:"a[cd]?"可以匹配 "a","ac","ad"+表达式至少出现1次,相当于 {1,},比如:"a+b"可以匹配 "ab","aab","aaab"...*表达式不出现或出现任意次,相当于 {0,},比如:"\^*b"可以匹配 "b","^^^b"...*前面的字符出现的次数任意
1 0