arjacsoh
arjacsoh

Reputation: 9232

Matching string using regex

I want to write a regular expression in a C++ program which checks if a string matches the following expression:

a word not containing '_' but it can contain number followed by

'_' followed by

three digits in a row (i.e. 047)

followed by '_' followed by

a string (can contain anything)

I have tried the following expression but it does seem to find the desired string as described above. I suspect the problem lies in the first part but I cannot detect it in order to modify properly:

static const wregex stringForm("([^_]?)_?(\\d{3})_(.+)");  

What is then the proper reg expression?

Upvotes: 0

Views: 236

Answers (2)

OrangeDog
OrangeDog

Reputation: 38749

\b[^_]*?(_\d{3}.+?)?\b

A word (\b is word boundary, quantifiers are non-greedy). Zero or more characters that aren't _ ([^_]*?). Optionally ((...)?), the digit sequence you described (_\d{3}) followed by one or more of any character (.+?).

Upvotes: 2

Besnik
Besnik

Reputation: 6529

Have you tried this:

static const wregex stringForm("([a-zA-Z0-9]*_[0-9]{3}.*)"); 

Upvotes: 0

Related Questions