tizen beta release
[framework/web/wrt-plugins-common.git] / src / Commons / RegexUtils.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 #include "RegexUtils.h"
17 #include <pcrecpp.h>
18 #include "StringUtils.h"
19
20 namespace WrtDeviceApis {
21 namespace Commons {
22
23 std::string addStartPositionMark(const std::string &value)
24 {
25     if (!String::startsWith(value, "^") && !String::startsWith(value, ".*")) {
26         return "^" + value;
27     }
28     return value;
29 }
30
31 std::string addEndPositionMark(const std::string &value)
32 {
33     if ((!String::endsWith(value, "$") || String::endsWith(value, "\\$")) &&
34         !String::endsWith(value, ".*")) {
35         return value + "$";
36     }
37     return value;
38 }
39
40 std::string addStartAndEndPositionMark(const std::string &value)
41 {
42     return addEndPositionMark(addStartPositionMark(value));
43 }
44
45 std::string preparePercent(const std::string& str)
46 {
47     std::string result = escape(str);
48     pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2\\\\*", &result);
49     pcrecpp::RE("(([^\\\\])%|^()%)").GlobalReplace("\\2.*", &result);
50     return result;
51 }
52
53 std::string prepareAsterisk(const std::string& str)
54 {
55     std::string result = escape(str);
56     // Replaces single wildcard "*" with version more compliant with Perl
57     // regular exrepssions, i.e. ".*".
58     pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2.*", &result);
59     return result;
60 }
61
62 std::string escape(const std::string& str)
63 {
64     std::string result = str;
65     // Escape standard regular expressions' metacharacters,
66     // i.e.: \, ., -, +, ?, (, ), [, ], ^, $, |
67     const char* metas = "(\\.|\\-|\\+|\\?|\\(|\\)|\\[|\\]|\\^|\\$|\\|"
68         "|(\\\\[^\\*\\%]|\\\\$))";                        // \*, \% won't get additional '\'
69     pcrecpp::RE(metas).GlobalReplace("\\\\\\1", &result);
70     return result;
71 }
72
73 }
74 } // WrtDeviceApisCommon