Passed
Push — master ( 96df68...2dc895 )
by
unknown
03:32
created

regex_substring()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
c 2
b 0
f 0
dl 0
loc 5
rs 9.4285
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  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
import re
17
import six
18
19
__all__ = [
20
    'regex_match',
21
    'regex_replace',
22
    'regex_search'
23
]
24
25
26
def _get_regex_flags(ignorecase=False):
27
    return re.I if ignorecase else 0
28
29
30
def regex_match(value, pattern='', ignorecase=False):
31
    if not isinstance(value, six.string_types):
32
        value = str(value)
33
    flags = _get_regex_flags(ignorecase)
34
    return bool(re.match(pattern, value, flags))
35
36
37
def regex_replace(value='', pattern='', replacement='', ignorecase=False):
38
    if not isinstance(value, six.string_types):
39
        value = str(value)
40
    flags = _get_regex_flags(ignorecase)
41
    regex = re.compile(pattern, flags)
42
    return regex.sub(replacement, value)
43
44
45
def regex_search(value, pattern='', ignorecase=False):
46
    if not isinstance(value, six.string_types):
47
        value = str(value)
48
    flags = _get_regex_flags(ignorecase)
49
    return bool(re.search(pattern, value, flags))
50
51
52
def regex_substring(value, pattern='', result_index=0, ignorecase=False):
53
    if not isinstance(value, six.string_types):
54
        value = str(value)
55
    flags = _get_regex_flags(ignorecase)
56
    return re.findall(pattern, value, flags)[result_index]
57