简体   繁体   中英

Validate input using regex

I honestly don't know what I am doing wrong. I have checked the regex expression in http://regexpal.com/ and it works just fine

here is my code:

std::string text = "1.98";
std::regex regex_number("((\b[0-9]+)?\.)?[0-9]+\b");  
bool isValid = std::regex_match(text, regex_number);

It should be valid for integers and doubles Ex:

  • 1.2
  • 1
  • 1.99
  • 0.6

Not valid for

  • aa
  • dd
  • 1.2h
  • 1,6

I get Non Valid text for everything.

您忘了在字符串文字中转义反斜杠:

std::regex regex_number("((\\b[0-9]+)?\\.)?[0-9]+\\b"); 

You also stuck that first word delimiter in the wrong spot. It should be outside the optional sections:

"\\b(([0-9]+)?\\.)?[0-9]+\\b"

(Sorry for the additional answer; I still don't have the rep to add comments.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM