├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Build 20 | run: cargo build --verbose 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/target/ 3 | __pycache__ 4 | *.so 5 | .vscode 6 | /tests/ 7 | /Cargo.lock 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "regex" 3 | version = "0.1.0" 4 | authors = ["Harrison Burt <57491488+ChillFish8@users.noreply.github.com>"] 5 | edition = "2018" 6 | 7 | [lib] 8 | name = "regex" 9 | crate-type = ["cdylib"] 10 | 11 | [dependencies.pyo3] 12 | version = "0.12.1" 13 | features = ["extension-module"] 14 | 15 | [dependencies] 16 | regex = "1.4.2" 17 | 18 | # faster memory allocator, seems to help PyO3 a decent amount 19 | mimalloc = { version = "*", default-features = false } 20 | 21 | [profile.release] 22 | lto = "fat" 23 | codegen-units = 1 24 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8 2 | 3 | ENV PYTHONUNBUFFERED 1 4 | 5 | RUN mkdir /temp 6 | WORKDIR /temp 7 | RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y 8 | ENV PATH="/root/.cargo/bin:${PATH}" 9 | 10 | RUN apt update 11 | RUN apt install cmake -y 12 | 13 | RUN mkdir /code 14 | COPY . /code/ 15 | WORKDIR /code 16 | RUN pip install maturin 17 | RUN ls -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Regex 2 | A port of the Rust regex library to python. 3 | 4 | This package aims to provide complete coverage of the [regex](https://github.com/rust-lang/regex) crate in Rust giving you all the advantages it brings: 5 | > An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs. 6 | 7 | Thanks to the linear time matching it allows Python-Regex to be roughly the same speed as the standard library for non-complicated or large matches while being able to cut matching times for large and complicated expressions into fractions of what they were. 8 | 9 | ## Example of where it excels 10 | 11 | In this example we use this regex pattern for selecting HTML tags. 12 | 13 | In this case when benched on a large chunk of HTML the Rust port took just `13ms` as a max value compared to Python's `116ms` value that grows almost exponentially as the text size increases. 14 | 15 | ```py 16 | import regex 17 | 18 | exp = regex.Regex( 19 | r"()|()|" 20 | r"()|(<\/?(\s|\S)*?>)".replace("\/", "/") 21 | ) 22 | 23 | exp.find("") 24 | ``` 25 | 26 | ## Todo: 27 | - finish adding all the other regex functions 28 | - build wheels 29 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | build-wheels: 5 | build: . 6 | command: maturin build --release 7 | volumes: 8 | - .:/code -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use pyo3::prelude::*; 2 | use pyo3::wrap_pyfunction; 3 | use pyo3::exceptions::PyValueError; 4 | 5 | use regex::{Regex, RegexSet}; 6 | 7 | use mimalloc::MiMalloc; 8 | 9 | 10 | /// Faster memory allocator in Pyo3 context 11 | #[global_allocator] 12 | static GLOBAL: MiMalloc = MiMalloc; 13 | 14 | /// Compiles and produces a regex class for matching strings to the regex 15 | /// pattern, it is recommended to use this over the function methods as 16 | /// compiling takes a while and shouldn't be constantly remade hurting performance. 17 | #[pyclass(name=Regex)] 18 | pub struct PyRegex { 19 | regex: Regex, 20 | } 21 | 22 | #[pymethods] 23 | impl PyRegex { 24 | #[new] 25 | fn new(pattern: &str) -> Self { 26 | PyRegex { regex: Regex::new(pattern).unwrap() } 27 | } 28 | 29 | /// Matches the compiled regex string to another string passed to this 30 | /// function. 31 | /// 32 | /// Args: 33 | /// other: 34 | /// The other string to be matched against the compiled regex 35 | /// 36 | /// Returns: 37 | /// A bool signifying if it is a match or not. 38 | fn is_match(&self, other: &str) -> bool { 39 | self.regex.is_match(other) 40 | } 41 | 42 | /// Matches the compiled regex string to another string passed to this 43 | /// function at a specific point marked by the start parameter. 44 | /// 45 | /// Args: 46 | /// other: 47 | /// The other string to be matched against the compiled regex. 48 | /// start: 49 | /// The starting index of the string you want to match against. 50 | /// 51 | /// Returns: 52 | /// A bool signifying if it is a match or not. 53 | fn is_match_at(&self, other: &str, start: usize) -> bool { 54 | self.regex.is_match_at(other, start) 55 | } 56 | 57 | /// Matches the compiled regex string to another string passed to this 58 | /// function, if a match is found it returns the matched string otherwise 59 | /// it returns None. 60 | /// 61 | /// Args: 62 | /// other: 63 | /// The other string to be matched against the compiled regex. 64 | /// 65 | /// Returns: 66 | /// Optional[str] - This can either be the matched text or None. 67 | fn find(&self, other: &str) -> Option { 68 | let matched = match self.regex.find(other) { 69 | Some(m) => m, 70 | _ => return None, 71 | }; 72 | 73 | Some(matched.as_str().to_string()) 74 | } 75 | 76 | /// Matches the compiled regex string to another string passed to this 77 | /// function and returns all matched strings in a list, if no matches it 78 | /// returns a empty list 79 | /// 80 | /// Args: 81 | /// other: 82 | /// The other string to be matched against the compiled regex. 83 | /// 84 | /// Returns: 85 | /// A list with n amount of text objects containing matched strings. 86 | fn findall(&self, other: &str) -> Vec { 87 | let matched: Vec = self.regex 88 | .find_iter(other) 89 | .map(|match_| { 90 | match_.as_str().to_string() 91 | }) 92 | .collect(); 93 | 94 | matched 95 | } 96 | 97 | /// Matches the compiled regex string to another string passed to this 98 | /// function and returns all matched groups that are captured by the notated, 99 | /// regex if non are matched it returns a empty list. 100 | /// 101 | /// Args: 102 | /// other: 103 | /// The other string to be matched against the compiled regex. 104 | /// 105 | /// Returns: 106 | /// A list with n amount of lists containing grouped matches relating 107 | /// to the compiled regex. 108 | fn all_captures(&self, other: &str) -> Vec>> { 109 | let mut caps = Vec::new(); 110 | for capture in self.regex.captures_iter(other) { 111 | let new = list_captures(capture); 112 | caps.push(new); 113 | } 114 | caps 115 | } 116 | 117 | /// Matches the compiled regex string to another string passed to this 118 | /// function and returns the first matched group according to the compiled 119 | /// regex pattern. 120 | /// 121 | /// Args: 122 | /// other: 123 | /// The other string to be matched against the compiled regex. 124 | /// 125 | /// Returns: 126 | /// A list with containing grouped matches relating 127 | /// to the compiled regex. 128 | fn captures(&self, other: &str) -> Option>> { 129 | let capture = match self.regex.captures(other) { 130 | Some(c) => c, 131 | _ => return None, 132 | }; 133 | let new = list_captures(capture); 134 | 135 | Some(new) 136 | } 137 | 138 | /// Function that given returns a vector of tuples that contain 139 | /// (start_match, end_match+1) according to the compiled regex. 140 | /// Args: 141 | /// other: 142 | /// The other string to be matched against the compiled regex. 143 | /// 144 | /// Returns: 145 | /// A vector of tuples that contain (start_match, end_match+1). 146 | fn matches(&self, other: &str) -> Vec<(usize, usize)> { 147 | let mut matches = Vec::new(); 148 | for m in self.regex.find_iter(other) { 149 | matches.push((m.start(), m.end())); 150 | } 151 | matches 152 | } 153 | } 154 | 155 | /// Compile several regex patterns into a RegexSet, this will match all patterns 156 | /// in a single match, if you have several patterns you want to check on the 157 | /// same string this system will be the most performance and efficient method. 158 | /// 159 | /// 160 | /// # Limitations 161 | /// Regex sets are limited to answering the following two questions: 162 | /// 163 | /// 1. Does any regex in the set match? 164 | /// 2. If so, which regexes in the set match? 165 | /// 166 | /// As with the main Regex type, it is cheaper to ask (1) instead of (2) 167 | /// since the matching engines can stop after the first match is found. 168 | /// 169 | /// Other features like finding the location of successive matches or their 170 | /// sub-captures aren't supported. If you need this functionality, the 171 | /// recommended approach is to compile each regex in the set independently 172 | /// and selectively match them based on which regexes in the set matched. 173 | /// 174 | /// 175 | /// # Performance 176 | /// A RegexSet has the same performance characteristics as Regex. Namely, 177 | /// search takes O(mn) time, where m is proportional to the size of the regex 178 | /// set and n is proportional to the length of the search text. 179 | #[pyclass(name=RegexSet)] 180 | struct PyRegexSet { 181 | set: RegexSet, 182 | } 183 | 184 | #[pymethods] 185 | impl PyRegexSet { 186 | #[new] 187 | fn new(pattern: Vec<&str>) -> PyResult { 188 | let set = RegexSet::new(pattern); 189 | 190 | let set = match set { 191 | Ok(s) => s, 192 | Err(e) => return Err(PyValueError::new_err(format!("{:?}", e))) 193 | }; 194 | 195 | Ok(PyRegexSet { 196 | set, 197 | }) 198 | } 199 | 200 | /// Checks if any of the compiled regex patterns in the set match. 201 | /// 202 | /// Args: 203 | /// other: 204 | /// The other string to be matched against the compiled set. 205 | /// 206 | /// Returns: 207 | /// A bool signifying if any patterns in the set match. 208 | fn is_match(&self, other: &str) -> bool { 209 | self.set.is_match(other) 210 | } 211 | 212 | /// Matches the string against the compiled set which will give a list of 213 | /// numbers representing which pattern(s) matches the string. 214 | /// 215 | /// Args: 216 | /// other: 217 | /// The other string to be matched against the compiled set. 218 | /// 219 | /// Returns: 220 | /// A list of ints which relates the the index of the pattern that was 221 | /// matched. The order of patterns is the same order as added. 222 | fn find(&self, other: &str) -> Vec { 223 | let matches = self.set.matches(other); 224 | 225 | let mut out_matches = Vec::with_capacity(self.set.len()); 226 | for match_ in matches.iter() { 227 | out_matches.push(match_) 228 | } 229 | 230 | out_matches 231 | } 232 | } 233 | 234 | 235 | fn list_captures(capture: regex::Captures) ->Vec> { 236 | let mut new: Vec> = capture 237 | .iter() 238 | .map(|m| { 239 | match m { 240 | Some(thing) => { 241 | Some(thing.as_str().to_string()) 242 | } 243 | _ => None, 244 | } 245 | }) 246 | .collect(); 247 | new.remove(0); 248 | 249 | new 250 | } 251 | 252 | /// Function that given a `regex_pattern` and an input `input_str` will produce 253 | /// the matching points of the start and end of the match. 254 | /// 255 | /// Args: 256 | /// regex_pattern: 257 | /// The regex pattern to be matched against a string. 258 | /// other: 259 | /// The other string to be matched against the compiled regex. 260 | /// 261 | /// Returns: 262 | /// A vector of tuples that contain (start_match, end_match+1). 263 | /// 264 | #[pyfunction] 265 | pub fn matches(regex_pattern: &str, other: &str) -> Vec<(usize, usize)> { 266 | let re = Regex::new(regex_pattern).unwrap(); 267 | let mut matches = Vec::new(); 268 | for m in re.find_iter(other) { 269 | matches.push((m.start(), m.end())); 270 | } 271 | matches 272 | } 273 | 274 | 275 | /// 276 | /// Wraps all our existing pyobjects together in the module 277 | /// 278 | #[pymodule] 279 | fn regex(_py: Python, m: &PyModule) -> PyResult<()> { 280 | m.add_class::()?; 281 | m.add_class::()?; 282 | m.add_function(wrap_pyfunction!(matches, m)?)?; 283 | Ok(()) 284 | } 285 | --------------------------------------------------------------------------------