1

I would like to remove all lines from a QString that have text and keep the ones that are numbers.

Prior to running a regexp my QString output be as so:

hello

1

world

2

if I ran something like

QString.remove(QRegExp("(^[a-z]*\\n$)"))

my QString output would be:

1

2
bandito40
  • 597
  • 1
  • 5
  • 15

1 Answers1

1

Since QRegExp does not have a Perl-like /m modifier, you need to use groups like (^|\n) and ($|\n) instead. Also, bearing in mind linebreaks may include carriage returns, I'd use something like

(^|\r?\n)[a-z]*\r?\n(\r?\n|$)

See the regex demo

Qt:

QString t = "hello\n\n1\n\nworld\n\n2";
t.replace(QRegExp("(^|\r?\n)[a-z]*\r?\n(\r?\n|$)"), "\\1");

NOTE that this code will only remove lines that only consist of lowercase ASCII letters and a linebreak after them. If you need to just remove all lines that are not numeric, use QRegExp("(^|\r?\n)[^\\d\n]+\r?\n(\r?\n|$)") where [^\d\n] matches any non-digit character and not a newline.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I couldn't get your example to work for my needs. I ended up just convert it to a QStringList and doing it line by line. The only reason I wanted to do it with a regexp was to save some lines of code. Thanks for they answer. – bandito40 May 01 '16 at 23:06
  • It is always difficult to help with multiline issues as there are a lot of nuances. Glad you found a way to solve your issue. – Wiktor Stribiżew May 01 '16 at 23:09