1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "negative_rule.h"
16 
17 namespace OHOS {
18 namespace Global {
19 namespace I18n {
NegativeRule(icu::UnicodeString & regex,std::string & insensitive)20 NegativeRule::NegativeRule(icu::UnicodeString& regex, std::string& insensitive)
21 {
22     this->regex = regex;
23     this->status = U_ZERO_ERROR;
24     this->insensitive = insensitive;
25     if (regex.length() == 0) {
26         return;
27     }
28 }
29 
GetPattern()30 icu::RegexPattern* NegativeRule::GetPattern()
31 {
32     // Sets whether regular expression matching is case sensitive
33     if (this->insensitive == "True") {
34         return icu::RegexPattern::compile(this->regex, URegexpFlag::UREGEX_CASE_INSENSITIVE, this->status);
35     } else {
36         return icu::RegexPattern::compile(this->regex, 0, this->status);
37     }
38 }
39 
ReplaceSpecifiedPos(icu::UnicodeString & chs,int start,int end)40 void NegativeRule::ReplaceSpecifiedPos(icu::UnicodeString& chs, int start, int end)
41 {
42     if (start < end) {
43         int len = chs.length();
44         for (int i = 0; i < len; i++) {
45             if (i >= start && i < end) {
46                 chs.replace(i, 1, 'A');
47             }
48         }
49     }
50 }
51 
Handle(icu::UnicodeString & src)52 icu::UnicodeString NegativeRule::Handle(icu::UnicodeString& src)
53 {
54     icu::UnicodeString ret = src;
55     icu::RegexPattern* pattern = GetPattern();
56     UErrorCode status = U_ZERO_ERROR;
57     icu::RegexMatcher* matcher = pattern->matcher(ret, status);
58     while (matcher != nullptr && matcher->find(status)) {
59         int start = matcher->start(status);
60         int end = matcher->end(status);
61         ReplaceSpecifiedPos(ret, start, end);
62     }
63     delete matcher;
64     delete pattern;
65     return ret;
66 }
67 } // namespace I18n
68 } // namespace Global
69 } // namespace OHOS