Scribbling

[C++] Regular Expression Matching 본문

Computer Science/C++

[C++] Regular Expression Matching

focalpoint 2024. 9. 26. 07:34

 

C++ Regular Expressions Library

https://en.cppreference.com/w/cpp/regex

 

Regular expressions library (since C++11) - cppreference.com

Regular expressions library The regular expressions library provides a class that represents regular expressions, which are a kind of mini-language used to perform pattern matching within strings. Almost all operations with regexes can be characterized by

en.cppreference.com

 

8. String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/description/

 

 

#include <iostream>
#include <regex>
#include <stdexcept>
#include <climits>

class Solution {
public:
    int myAtoi(string s) {
        const std::regex pat("^ *([+-]?)([0-9]+)");
		std::smatch match;
		std::regex_search(s, match, pat);
		if (match.size() == 0) return 0;
		string sign = match.str(1);
		int parsed;
		try {
			parsed = stoi(match.str(2));
		} catch (std::out_of_range& e) {
			if (!sign.empty() and sign == "-")
                return INT_MIN;
            return INT_MAX;
		} 
		if (!sign.empty() and sign == "-") 
			return -parsed;
		return parsed;
    }
};

 

 

'Computer Science > C++' 카테고리의 다른 글

[C++] Abstract Class, Polymorphism  (0) 2024.09.28
[C++] Virtual Functions  (0) 2024.09.28
[C++] Priority Queue with custom data type  (0) 2024.02.22
[C++] Abstract Class, Interface, Multiple Inheritance  (0) 2024.02.14
[C++] lower_bound  (0) 2024.02.06