Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Strings by slashes

Tags:

string

split

qt

I'm just wondering how i can split a string by both front slashes (/) & backslashes (). So for example, these types of strings;

"X:/Blah/blah/"
"X:\Blah\blah\"

And also mixed slashes;

"X:/Blah\blah/"

Would work & in each case return: "X:", "Blah", "blah"

I believe i will need to use a QRegExp, http://doc.qt.io/archives/qt-4.7/qregexp.html but i'm just not sure what character set i will need to use.

like image 276
Danran Avatar asked Mar 02 '26 13:03

Danran


2 Answers

str.split( QRegExp("[/\\\\]") );

The regex needs two backslashes to prevent the backslash character from escaping the ] character, and C++ adds an additional two so that you're passing in \ literals.

like image 71
Chris Avatar answered Mar 04 '26 03:03

Chris


If you are parsing file names, how about using QFileInfo?

QFileInfo fileInfo("c:\\test folder\\one\\test\\three.avi");

That will convert everything to forward slashes. When you output the absolute path:

qDebug() << fileInfo.absolutePath();

The output will just have forward slashes like this:

"C:/test folder/one/test"

You can then use the regular split command as so to get the components:

QStringList fileParts = fileInfo.absolutePath().split("/");
like image 29
mzelina Avatar answered Mar 04 '26 03:03

mzelina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!