• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "i18n_hilog.h"
16 #include "negative_rule.h"
17 #include "i18n_hilog.h"
18 
19 namespace OHOS {
20 namespace Global {
21 namespace I18n {
NegativeRule(icu::UnicodeString & regex,std::string & insensitive)22 NegativeRule::NegativeRule(icu::UnicodeString& regex, std::string& insensitive)
23 {
24     this->regex = regex;
25     this->insensitive = insensitive;
26 }
27 
GetPattern()28 icu::RegexPattern* NegativeRule::GetPattern()
29 {
30     UErrorCode status = U_ZERO_ERROR;
31     icu::RegexPattern* pattern;
32     // Sets whether regular expression matching is case sensitive
33     if (this->insensitive == "True") {
34         pattern = icu::RegexPattern::compile(this->regex, URegexpFlag::UREGEX_CASE_INSENSITIVE, status);
35     } else {
36         pattern = icu::RegexPattern::compile(this->regex, 0, status);
37     }
38     if (U_FAILURE(status)) {
39         HILOG_ERROR_I18N("NegativeRule::GetPattern: Compile regex pattern failed.");
40         return nullptr;
41     }
42     return pattern;
43 }
44 
ReplaceSpecifiedPos(icu::UnicodeString & chs,int start,int end)45 void NegativeRule::ReplaceSpecifiedPos(icu::UnicodeString& chs, int start, int end)
46 {
47     if (start < end) {
48         int len = chs.length();
49         for (int i = 0; i < len; i++) {
50             if (i >= start && i < end) {
51                 chs.replace(i, 1, 'A');
52             }
53         }
54     }
55 }
56 
Handle(icu::UnicodeString & src)57 icu::UnicodeString NegativeRule::Handle(icu::UnicodeString& src)
58 {
59     icu::UnicodeString ret = src;
60     icu::RegexPattern* pattern = GetPattern();
61     if (pattern == nullptr) {
62         HILOG_ERROR_I18N("NegativeRule::Handle: pattern is nullptr.");
63         return ret;
64     }
65     UErrorCode status = U_ZERO_ERROR;
66     icu::RegexMatcher* matcher = pattern->matcher(ret, status);
67     while (matcher != nullptr && matcher->find(status)) {
68         int start = matcher->start(status);
69         int end = matcher->end(status);
70         ReplaceSpecifiedPos(ret, start, end);
71     }
72     delete matcher;
73     delete pattern;
74     return ret;
75 }
76 } // namespace I18n
77 } // namespace Global
78 } // namespace OHOS