1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/autofill/autofill_regexes.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/singleton.h"
13 #include "base/stl_util.h"
14 #include "base/string16.h"
15 #include "unicode/regex.h"
19 // A singleton class that serves as a cache of compiled regex patterns.
20 class AutofillRegexes
{
22 static AutofillRegexes
* GetInstance();
24 // Returns the compiled regex matcher corresponding to |pattern|.
25 icu::RegexMatcher
* GetMatcher(const string16
& pattern
);
30 friend struct DefaultSingletonTraits
<AutofillRegexes
>;
32 // Maps patterns to their corresponding regex matchers.
33 std::map
<string16
, icu::RegexMatcher
*> matchers_
;
35 DISALLOW_COPY_AND_ASSIGN(AutofillRegexes
);
39 AutofillRegexes
* AutofillRegexes::GetInstance() {
40 return Singleton
<AutofillRegexes
>::get();
43 AutofillRegexes::AutofillRegexes() {
46 AutofillRegexes::~AutofillRegexes() {
47 STLDeleteContainerPairSecondPointers(matchers_
.begin(),
51 icu::RegexMatcher
* AutofillRegexes::GetMatcher(const string16
& pattern
) {
52 if (!matchers_
.count(pattern
)) {
53 const icu::UnicodeString
icu_pattern(pattern
.data(), pattern
.length());
55 UErrorCode status
= U_ZERO_ERROR
;
56 icu::RegexMatcher
* matcher
= new icu::RegexMatcher(icu_pattern
,
57 UREGEX_CASE_INSENSITIVE
,
59 DCHECK(U_SUCCESS(status
));
61 matchers_
.insert(std::make_pair(pattern
, matcher
));
64 return matchers_
[pattern
];
71 bool MatchesPattern(const string16
& input
, const string16
& pattern
) {
72 icu::RegexMatcher
* matcher
=
73 AutofillRegexes::GetInstance()->GetMatcher(pattern
);
74 icu::UnicodeString
icu_input(input
.data(), input
.length());
75 matcher
->reset(icu_input
);
77 UErrorCode status
= U_ZERO_ERROR
;
78 UBool match
= matcher
->find(0, status
);
79 DCHECK(U_SUCCESS(status
));
83 } // namespace autofill