Search code examples
regexwindowsip-addressqregexpqt5.2

How to allow "*" and number only in Regular Expression : Qt5.2


I want to allow * or Number only in my QLineEdit for IP Address.

My regular Expression is:

QRegExp rx ( "^(0|[1-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))$" );

Which is find for IP Address, Now I want to allow * symbol for search IP Range.

i.e. 10.105.*.* to 10.107.*.* This treated as 10.105.0.0 to 10.107.255.255


Solution

  • Try this Regex which matches IPAddress with * and/or between 0-255

    Regex reg = new Regex("^((\\*)?|[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.((\\*)?|[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.((\\*)?|[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.((\\*)?|[01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
    
    bool isMatch = reg.IsMatch("*.1.1.255"); //true
    isMatch=reg.IsMatch("255.255.255.255"); //true
    isMatch=reg.IsMatch("*.*.*.*"); //true
    isMatch=reg.IsMatch("0.0.0.0"); //true
    isMatch=reg.IsMatch("256.*.*.*);//false
    isMatch=reg.IsMatch("2.2.455.*);//false