Qt学习:正则表达式 - QRegExp


用正则表达式验证文本有效性
你可以使用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 f
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值