1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
use rand::Rng;
use std::collections::HashMap;
use std::collections::HashSet;
pub struct RegexGenerator {
pattern: String,
groups: HashMap<usize, String>,
increment_value: Option<String>,
direction: i32, // 1 for ascending, -1 for descending
array_values: Option<Vec<String>>, // Optional array of strings
array_index: usize, // Index to track ascending or descending order
}
impl RegexGenerator {
pub fn new(pattern: &str, increment_value: Option<String>, array_values: Option<Vec<String>>) -> Self {
Self {
pattern: pattern.to_string(),
groups: HashMap::new(),
increment_value,
direction: 1, // default to ascending
array_values, // store the array of strings
array_index: 0, // start at the beginning of the array
}
}
pub fn generate(&mut self) -> String {
let mut result = String::new();
let mut chars = self.pattern.chars().peekable();
let mut group_stack: Vec<String> = Vec::new();
let mut current_group: Option<usize> = None;
let mut group_index: usize = 1;
while let Some(ch) = chars.next() {
if ch == '\\' {
if let Some(next_ch) = chars.next() {
match next_ch {
'i' => {
// Check for + or - sign
let sign = if chars.peek() == Some(&'+') {
chars.next();
1 // Ascending
} else if chars.peek() == Some(&'-') {
chars.next();
-1 // Descending
} else {
1 // Default to ascending
};
self.direction = sign;
// Check for leading zero specifier {:total_len}
let total_len = if chars.peek() == Some(&'{') {
chars.next(); // Skip the '{'
let mut spec = String::new();
while let Some(&c) = chars.peek() {
if c == '}' {
chars.next(); // Skip the '}'
break;
}
if c != ':' && c.is_numeric() {
spec.push(c);
}
chars.next();
}
spec.parse::<usize>().ok()
} else {
None
};
if let Some(increment_value) = self.increment_value.take() {
let new_value = self.increment_string(&increment_value, total_len);
result.push_str(&new_value);
self.increment_value = Some(new_value);
} else {
result.push_str("0"); // Default to "0" or another placeholder
}
}
'a' => {
let array_sign = if chars.peek() == Some(&'+') {
chars.next();
1 // Ascending
} else if chars.peek() == Some(&'-') {
chars.next();
-1 // Descending
} else {
0 // Random
};
if let Some(ref array) = self.array_values {
match array_sign {
1 => {
// Ascending order
let value = &array[self.array_index % array.len()];
result.push_str(value);
self.array_index += 1;
}
-1 => {
// Descending order
let index = array.len() - 1 - (self.array_index % array.len());
let value = &array[index];
result.push_str(value);
self.array_index += 1;
}
_ => {
// Random order
let mut rng = rand::thread_rng();
let random_string = &array[rng.gen_range(0..array.len())];
result.push_str(random_string);
}
}
} else {
result.push_str(""); // If no array is provided, insert nothing or handle as needed
}
}
'1'..='9' => {
if let Some(content) = self.groups.get(&(next_ch.to_digit(10).unwrap() as usize)) {
result.push_str(content);
}
}
_ => {
if let Some(repeat_spec) = self.check_repeat_spec(&mut chars) {
result.push_str(&self.handle_repeat(next_ch, repeat_spec));
} else {
result.push_str(&self.handle_escape(next_ch));
}
}
}
}
} else if ch == '[' {
let (char_class, negate) = self.extract_char_class(&mut chars);
if let Some(repeat_spec) = self.check_repeat_spec(&mut chars) {
result.push_str(&self.handle_bracket(char_class, repeat_spec, negate));
} else {
result.push_str(&self.handle_bracket(char_class, (1, None, None), negate));
}
} else if ch == '(' {
if chars.peek() == Some(&'?') {
chars.next(); // Skip the '?'
// Handle non-capturing groups or other special groups here
}
current_group = Some(group_index);
group_stack.push(String::new());
group_index += 1;
} else if ch == ')' {
if let Some(group) = current_group {
if let Some(mut content) = group_stack.pop() {
if let Some(_alt_pos) = content.find('|') {
let choices: Vec<&str> = content.split('|').collect();
content = choices[0].to_string();
}
self.groups.insert(group, content.clone());
result.push_str(&content);
current_group = None;
}
}
} else if ch == '|' {
if let Some(last) = group_stack.last_mut() {
last.push('|');
} else {
result.push('|');
}
} else {
if let Some(ref mut _current) = current_group {
if let Some(last) = group_stack.last_mut() {
last.push(ch);
}
} else {
result.push(ch);
}
}
}
result
}
fn check_repeat_spec<I>(&self, chars: &mut std::iter::Peekable<I>) -> Option<(usize, Option<usize>, Option<(usize, usize)>)>
where
I: Iterator<Item = char>,
{
if chars.peek() == Some(&'{') {
chars.next(); // Skip the '{'
let mut spec = String::new();
while let Some(&c) = chars.peek() {
if c == '}' {
chars.next(); // Skip the '}'
break;
}
spec.push(c);
chars.next();
}
if let Some(colon_pos) = spec.find(':') {
// Handle leading zeros pattern {num_len:total_len}
let num_len = spec[..colon_pos].parse().ok()?;
let total_len = spec[colon_pos + 1..].parse().ok()?;
return Some((1, None, Some((num_len, total_len))));
} else {
// Handle regular repeat pattern {min,max}
let parts: Vec<&str> = spec.split(',').collect();
if parts.len() == 1 {
return Some((parts[0].parse().unwrap(), None, None));
} else if parts.len() == 2 {
return Some((parts[0].parse().unwrap(), Some(parts[1].parse().unwrap()), None));
}
}
}
None
}
fn handle_escape(&self, ch: char) -> String {
let mut rng = rand::thread_rng();
match ch {
'd' => rng.gen_range(0..10).to_string(), // \d - any digit
'w' => {
let sample_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
sample_set.chars().nth(rng.gen_range(0..sample_set.len())).unwrap().to_string()
} // \w - any word character
's' => {
let sample_set = " \t\n\r";
sample_set.chars().nth(rng.gen_range(0..sample_set.len())).unwrap().to_string()
} // \s - any whitespace
'D' => {
let sample_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()";
sample_set.chars().nth(rng.gen_range(0..sample_set.len())).unwrap().to_string()
} // \D - any non-digit character
'W' => {
let sample_set = "!@#$%^&*()+=-[]{}|;:,.<>?/`~";
sample_set.chars().nth(rng.gen_range(0..sample_set.len())).unwrap().to_string()
} // \W - any non-word character
'S' => {
let sample_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
sample_set.chars().nth(rng.gen_range(0..sample_set.len())).unwrap().to_string()
} // \S - any non-whitespace character
't' => "\t".to_string(), // \t - Tab character
'n' => "\n".to_string(), // \n - Line feed character
_ => ch.to_string(),
}
}
fn handle_repeat(&self, ch: char, repeat_spec: (usize, Option<usize>, Option<(usize, usize)>)) -> String {
let (min, max, leading_zeros_spec) = repeat_spec;
let mut rng = rand::thread_rng();
let repeat_count = if let Some(max) = max {
rng.gen_range(min..=max)
} else {
min
};
if let Some((num_len, total_len)) = leading_zeros_spec {
// Handle leading zeros pattern
let number = rng.gen_range(10_usize.pow((num_len - 1) as u32)..10_usize.pow(num_len as u32));
return format!("{:0width$}", number, width = total_len);
} else {
// Handle regular repeat pattern
return std::iter::repeat(self.handle_escape(ch))
.take(repeat_count)
.collect();
}
}
fn extract_char_class<I>(&self, chars: &mut std::iter::Peekable<I>) -> (HashSet<char>, bool)
where
I: Iterator<Item = char>,
{
let mut char_class = HashSet::new();
let mut negate = false;
let mut range_start = None;
if chars.peek() == Some(&'^') {
chars.next();
negate = true;
}
while let Some(ch) = chars.next() {
if ch == ']' {
break;
} else if ch == '-' && range_start.is_some() {
if let Some(range_end) = chars.next() {
let start = range_start.unwrap();
for c in start..=range_end {
char_class.insert(c);
}
range_start = None;
}
} else {
range_start = Some(ch);
char_class.insert(ch);
}
}
(char_class, negate)
}
fn handle_bracket(&self, char_class: HashSet<char>, repeat_spec: (usize, Option<usize>, Option<(usize, usize)>), negate: bool) -> String {
let (min, max, leading_zeros_spec) = repeat_spec;
let mut rng = rand::thread_rng();
let repeat_count = if let Some(max) = max {
rng.gen_range(min..=max)
} else {
min
};
if let Some((num_len, total_len)) = leading_zeros_spec {
// Handle leading zeros pattern
let number = rng.gen_range(10_usize.pow((num_len - 1) as u32)..10_usize.pow(num_len as u32));
return format!("{:0width$}", number, width = total_len);
} else {
let sample_set: Vec<char> = if negate {
let full_set: HashSet<char> = (32..127).map(|c| c as u8 as char).collect();
full_set.difference(&char_class).cloned().collect()
} else {
char_class.into_iter().collect()
};
return (0..repeat_count)
.map(|_| sample_set[rng.gen_range(0..sample_set.len())])
.collect();
}
}
fn increment_string(&self, value: &str, total_len: Option<usize>) -> String {
let mut prefix = String::new();
let mut digits = String::new();
// Separate prefix and numeric part
for ch in value.chars() {
if ch.is_digit(10) {
digits.push(ch);
} else {
if digits.is_empty() {
prefix.push(ch);
} else {
break;
}
}
}
// Adjust numeric part based on the direction (ascending or descending)
if let Ok(num) = digits.parse::<i32>() {
let adjusted_num = num + self.direction;
digits = if let Some(total_len) = total_len {
format!("{:0width$}", adjusted_num, width = total_len)
} else {
format!("{}", adjusted_num)
};
}
// Combine prefix and adjusted numeric part
format!("{}{}", prefix, digits)
}
}