用正则表达式验证文本有效性
你可以使用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