0

I want to create a Regular Expression which will only the input string to contain only [G|y|M|d|D|F|E|h|H|m|s|S|w|W|a|z|Z] so I come up with some code from below:

std::regex Reg = regex("[G|y|M|d|D|F|E|h|H|m|s|S|w|W|a|z|Z]");

My problem is that my regex still not correct because my input string can contain other characters with the characters in the above group such as:

std::string myInputString = Gx //correct

Which Gx has to be wrong

0

2 Answers 2

1

I’m not a user of C++’s regex lib, but I understand it supports ECMAScript syntax. So I don’t think you need the pipe characters. The “any character in set” [] syntax doesn’t use pipes. Secondly, if you want to match the entire input string (instead of any part of it) you need to use the ^ and $ anchors

Try:

std::regex( "^[GyMdDFEhHmsSwWazZ]+$" );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Dai, although mine is also working but you seem to look simpler.
@NguyễnĐứcTâm If you have the | character within the square-brackets then it will match it, so if the input string is "Z|a" then that will be treated as valid. I don't think that's what you want.
1

What i can understand from your question is that, you want to input string with those chosen characters only

the regex is correct up to my knowledge

but you need to compare the string char by char because if you are not doing that you might get the similar results like you are getting now...

1 Comment

I don't think it is necessary to compare char by char. std::regex regex("^[G|y|M|d|D|F|E|h|H|m|s|S|w|W|a|z|Z| |?]+$"); and then use regex_match It will worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.