Home Regex in C++ how to search for valid Linux Device Node?
Reply: 2

Regex in C++ how to search for valid Linux Device Node?

Frederick Ollinger
Frederick Ollinger Published in 2018-01-12 17:50:09Z

Given a device node in Linux such as "/dev/sda1" or "/dev/sdb", I'd like to match all valid choices to know if I have a valid device node.

Here's what I have so far:

static bool isUSBNameValid(const std::string &node) {
    std::regex device("/dev/sd[a-z]*");

    if (std::regex_match(node, device)) {
            return true;

    return false;

This does not work. Why is this?

How to make this work with any valid Linux device node?

michalsrb Reply to 2018-01-12 22:44:03Z

I would suggest the following pattern instead:

std::regex device("/dev/sd[a-z][0-9]*");

Add capturing groups around the [a-z] and [0-9]* if that becomes important.

If you truly want to match any device it would be:

std::regex device("/dev/[[::anum]]+");

with an additional check that what you have matched is not a directory. It would probably be good to add such a check (using stat) anyway.

Wiktor Stribi┼╝ew
Wiktor Stribi┼╝ew Reply to 2018-01-12 22:24:43Z

Your /dev/sd[a-z]* pattern matches /dev/sd literal substring followed with any 0+ lowercase ASCII letters. Used within regex_match, the pattern must match the whole string. Since the /dev/sda1 ends with a digit, the regex_match fails, but it succeeds with /dev/sdb.

So, if you plan to only match SATA devices, you will need to use /dev/sd[a-z][0-9]* pattern, else, to match arbitrary number of alphanumeric chars after /dev/, you may use /dev/[[:alnum:]]+.

std::regex device_sata("/dev/sd[a-z][0-9]*");
std::regex device_any("/dev/[[:alnum:]]+");

See the C++ demo:

#include <iostream>
using namespace std;

bool isUSBNameValid(const std::string &node, std::regex device) {
    if (std::regex_match(node, device)) {
            return true;
    return false;
int main() {
    std::regex device_sata("/dev/sd[a-z][0-9]*");
    std::regex device_any("/dev/[[:alnum:]]+");
    cout<< ( isUSBNameValid("/dev/sda1", device_sata) ? "Found" : "Not found")<<endl;
    cout<< ( isUSBNameValid("/dev/sdb", device_sata) ? "Found" : "Not found")<<endl;
    cout<< ( isUSBNameValid("/dev/ttyS0", device_any) ? "Found" : "Not found")<<endl;
    return 0;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.346745 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO