Added some regex examples.

This commit is contained in:
Stephen M. McQuay 2012-05-25 08:49:38 -06:00
parent 530ccb5e37
commit 0a9c36b286
3 changed files with 60 additions and 2 deletions

View File

@ -12,7 +12,7 @@ CPPFLAGS=-Wall -g -std=c++0x -pthread
# CXX=clang++ # CXX=clang++
# CPPFLAGS=-Wall -g -std=c++0x -stdlib=libc++ -L/opt/clang/lib -pthread # CPPFLAGS=-Wall -g -std=c++0x -stdlib=libc++ -L/opt/clang/lib -pthread
all: auto constexpr ilists init init_new lambda loops thread thread2 tuple all: auto constexpr ilists init init_new lambda loops regex1 regex2 thread thread2 tuple
run: all run: all
./auto ./auto
@ -25,7 +25,9 @@ run: all
./thread ./thread
./thread2 ./thread2
./tuple ./tuple
echo "1 11 1.1 1.1E12 stephen" | ./regex2
echo "hello cruel 12 world 12.22. you are 12.12 awesome!!" | ./regex2
clean: clean:
@rm -vf auto constexpr ilists init init_new lambda loops thread thread2 tuple @rm -vf auto constexpr core* ilists init init_new lambda loops regex1 regex2 thread thread2 tuple

28
regex1.cc Normal file
View File

@ -0,0 +1,28 @@
// from https://github.com/sol-prog/regex_tutorial
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
string input;
// traditional pcre escape
regex int_re {"(\\+|-)?\\d+"};
// ecmascript
regex float_re {"((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?((e|E)((\\+|-)?)[[:digit:]]+)?"};
while(cin >> input){
if (regex_match(input, int_re)) {
cout << "integer" << endl;
}
else if(regex_match(input, float_re)) {
cout << "float" << endl;
}
else {
cout << "nan" <<endl;
}
}
}

28
regex2.cc Normal file
View File

@ -0,0 +1,28 @@
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
//This should match any real number
regex number {"((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?((e|E)((\\+|-)?)[[:digit:]]+)?\\b"};
//This should match any word
regex word {"[[:alpha:]]+"};
regex space {"\\s+"};
string input, clean_words, clean_numbers;
//Replace with an empty string
const string format {""};
getline(cin,input);
//Split the input string in numbers and words
clean_numbers=regex_replace(input, number, format);
clean_words=regex_replace(input, word, format);
cout << clean_words << endl;
cout << clean_numbers << endl;
return 0;
}