momor10
momor10

Reputation: 498

QRegularExpression escape Asterisk as Character

I'm trying to match strings which look either like this:

7;7;52*8    
8;8;62*5    
9;9;55*1    
11;7;52*49    
12;8;62*64    
14;9;54*62

or like this:

7;7;52    
8;8;62    
9;9;55    
11;7;52    
12;8;62    
14;9;54

I'm using the following code.

QRegularExpression re("(^\\d+;\\d+;\\d\\d$)|(^\\d+;\\d+;\\d\\d\\*\\d+$)");
QRegularExpressionMatch match;

matching the first part is working, but the second one seems to break at the asterisk part.

The following code is working for the regex search in notepad++

(^\d+;\d+;\d\d$)|(^\d+;\d+;\d\d\*\d+$)

Is there some special way to escape the asterisk character?

Upvotes: 1

Views: 1097

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

It seems that you need to make the regex match the start and end of lines. The easiest way to fix the regex is to add (?m) inline modifier at the start of your pattern.

Note that your pattern contains redundant parts, you may use a regex with a single branch:

 "(?m)^\\d+;\\d+;\\d\\d(?:\\*\\d+)?$"

Details:

  • (?m)^ - start of a line
  • \\d+;\\d+; - 1+ digits and ; (2 times)
  • \\d\\d - two digits
  • (?:\\*\\d+)? - an optional sequence of a * and 1+ digits
  • $ - end of a line.

Upvotes: 1

Related Questions