Newer
Older
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
if (lines[i].match(regexp)) {
// The regex matches lines[i]
} else {
// The regex does not match lines[i]
}
}</pre>
<h4>PHP</h4>
<pre>$lines = preg_split('/\r?\n/', $subject)</pre>
<pre>foreach ($lines as $line) {
if (preg_match('/regex pattern/', $line)) {
// The regex matches $line
} else {
// The regex does not match $line
}
}</pre>
<h4>Perl</h4>
<pre>@lines = split(m/\r?\n/, $subject)</pre>
<pre>foreach $line (@lines) {
if ($line =~ m/regex pattern/) {
# The regex matches $line
} else {
# The regex does not match $line
}
}</pre>
<h4>Python</h4>
<pre>lines = re.split("\r?\n", subject)</pre>
<pre>reobj = re.compile("regex pattern")
for line in lines[:]:
if reobj.search(line):
# The regex matches line
else:
# The regex does not match line</pre>
<h4>Ruby</h4>
<pre>lines = subject.split(/\r?\n/)</pre>
<pre>re = /regex pattern/
lines.each { |line|
if line =~ re
# The regex matches line
else
# The regex does not match line
}</pre>
<h2>3.22. Construct a Parser</h2>
<h3>Problem</h3>
<pre>table %First table%
row cell %A1% cell %B1% cell%C1%cell%D1%
ROW row CELL %The previous row was blank%
cell %B3%
row
cell %A4% %second line%
cEll %B4%
%second line%
cell %C4
second line%
row cell %%%string%%%
cell %%
cell %%%%
cell %%%%%%</pre>
<h3>Solution</h3>
<h4>C#</h4>
<pre>static RECTable ImportTable(string fileContents) {
RECTable table = null;
RECRow row = null;
RECCell cell = null;
Regex regexObj = new Regex(
@" \b(?<keyword>table|row|cell)\b
| %(?<string>[^%]*(?:%%[^%]*)*)%
| (?<error>\S+)",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Match match = regexObj.Match(fileContents);
while (match.Success) {
if (match.Groups["keyword"].Success) {
string keyword = match.Groups["keyword"].Value.ToLower();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (table == null)
throw new Exception("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (row == null)
throw new Exception("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} else if (match.Groups["string"].Success) {
string content = match.Groups["string"].Value.Replace("%%", "%");
if (cell != null)
cell.addContent(content);
else if (row != null)
throw new Exception("Invalid data: string after row keyword");
else if (table != null)
table.addCaption(content);
else
throw new Exception("Invalid data: string before table keyword");
} else if (match.Groups["error"].Success) {
throw new Exception("Invalid data: " + match.Groups["error"].Value);
} else {
throw new Exception("Parser bug: no capturing group matched");
}
match = match.NextMatch();
}
if (table == null)
throw new Exception("Invalid data: table keyword missing");
return table;
}</pre>
<h4>VB.NET</h4>
<pre>Function ImportTable(ByVal FileContents As String)
Dim Table As RECTable = Nothing
Dim Row As RECRow = Nothing
Dim Cell As RECCell = Nothing
Dim RegexObj As New Regex(
" \b(?<keyword>table|row|cell)\b" & _
"| %(?<string>[^%]*(?:%%[^%]*)*)%" & _
"| (?<error>\S+)",
RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
Dim MatchResults As Match = RegexObj.Match(FileContents)
While MatchResults.Success
If MatchResults.Groups("keyword").Success Then
Dim Keyword As String = MatchResults.Groups("keyword").Value
Keyword = Keyword.ToLower()
If Keyword = "table" Then
Table = New RECTable
Row = Nothing
Cell = Nothing
ElseIf Keyword = "row" Then
If Table Is Nothing Then
Throw New Exception("Invalid data: row without table")
End If
Row = Table.addRow
Cell = Nothing
ElseIf Keyword = "cell" Then
If Row Is Nothing Then
Throw New Exception("Invalid data: cell without row")
End If
Cell = Row.addCell
Else
Throw New Exception("Parser bug: unknown keyword")
End If
ElseIf MatchResults.Groups("string").Success Then
Dim Content As String = MatchResults.Groups("string").Value
Content = Content.Replace("%%", "%")
If Cell IsNot Nothing Then
Cell.addContent(Content)
ElseIf Row IsNot Nothing Then
Throw New Exception("Invalid data: string after row keyword")
ElseIf Table IsNot Nothing Then
Table.addCaption(Content)
Else
Throw New Exception("Invalid data: string before table keyword")
End If
ElseIf MatchResults.Groups("error").Success Then
Throw New Exception("Invalid data")
Else
Throw New Exception("Parser bug: no capturing group matched")
End If
MatchResults = MatchResults.NextMatch()
End While
If Table Is Nothing Then
Throw New Exception("Invalid data: table keyword missing")
End If
Return Table
End Function</pre>
<h4>Java</h4>
<pre>RECTable ImportTable(String fileContents) throws Exception {
RECTable table = null;
RECRow row = null;
RECCell cell = null;
final int groupkeyword = 1;
final int groupstring = 2;
final int grouperror = 3;
Pattern regex = Pattern.compile(
" \\b(table|row|cell)\\b\n" +
"| %([^%]*(?:%%[^%]*)*)%\n" +
"| (\\S+)",
Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(fileContents);
while (regexMatcher.find()) {
if (regexMatcher.start(groupkeyword) >= 0) {
String keyword = regexMatcher.group(groupkeyword).toLowerCase();
if (keyword.equals("table")) {
table = new RECTable();
row = null;
cell = null;
} else if (keyword.equals("row")) {
if (table == null)
throw new Exception("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword.equals("cell")) {
if (row == null)
throw new Exception("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} else if (regexMatcher.start(groupstring) >= 0) {
String content = regexMatcher.group(groupstring);
content = content.replaceAll("%%", "%");
if (cell != null)
cell.addContent(content);
else if (row != null)
throw new Exception("Invalid data: String after row keyword");
else if (table != null)
table.addCaption(content);
else
throw new Exception("Invalid data: String before table keyword");
} else if (regexMatcher.start(grouperror) >= 0) {
throw new Exception("Invalid data: " +
regexMatcher.group(grouperror));
} else {
throw new Exception("Parser bug: no capturing group matched");
}
}
if (table == null)
throw new Exception("Invalid data: table keyword missing");
return table;
}</pre>
<h4>JavaScript</h4>
<pre>function importTable(fileContents) {
var table = null;
var row = null;
var cell = null;
var groupkeyword = 1;
var groupstring = 2;
var grouperror = 3;
var myregexp = /\b(table|row|cell)\b|%([^%]*(?:%%[^%]*)*)%|(\S+)/ig;
var match;
var keyword;
var content;
while (match = myregexp.exec(fileContents)) {
if (match[groupkeyword] !== undefined) {
keyword = match[groupkeyword].toLowerCase();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (!table)
throw new Error("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (!row)
throw new Error("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Error("Parser bug: unknown keyword");
}
} else if (match[groupstring] !== undefined) {
content = match[groupstring].replace(/%%/g, "%");
if (cell)
cell.addContent(content);
else if (row)
throw new Error("Invalid data: string after row keyword");
else if (table)
table.addCaption(content);
else
throw new Error("Invalid data: string before table keyword");
} else if (match[grouperror] !== undefined) {
throw new Error("Invalid data: " + match[grouperror]);
} else {
throw new Error("Parser bug: no capturing group matched");
}
}
if (!table)
throw new Error("Invalid data: table keyword missing");
return table;
}</pre>
<h4>XRegExp</h4>
<pre>function importTable(fileContents) {
var table = null;
var row = null;
var cell = null;
var myregexp = XRegExp("(?ix)\\b(?<keyword>table|row|cell)\\b" +
" | %(?<string>[^%]*(?:%%[^%]*)*)%" +
" | (?<error>\\S+)");
XRegExp.forEach(fileContents, myregexp, function(match) {
var keyword;
var content;
if (match.keyword !== undefined) {
keyword = match.keyword.toLowerCase();
if (keyword == "table") {
table = new RECTable();
row = null;
cell = null;
} else if (keyword == "row") {
if (!table)
throw new Error("Invalid data: row without table");
row = table.addRow();
cell = null;
} else if (keyword == "cell") {
if (!row)
throw new Error("Invalid data: cell without row");
cell = row.addCell();
} else {
throw new Error("Parser bug: unknown keyword");
}
} else if (match.string !== undefined) {
content = match.string.replace(/%%/g, "%");
if (cell)
cell.addContent(content);
else if (row)
throw new Error("Invalid data: string after row keyword");
else if (table)
table.addCaption(content);
else
throw new Error("Invalid data: string before table keyword");
} else if (match.error !== undefined) {
throw new Error("Invalid data: " + match.error);
} else {
throw new Error("Parser bug: no capturing group matched");
}
});
if (!table)
throw new Error("Invalid data: table keyword missing");
return table;
}</pre>
<h4>Perl</h4>
<pre>sub importtable {
my $filecontents = shift;
my $table;
my $row;
my $cell;
while ($filecontents =~
m/ \b(table|row|cell)\b
| %([^%]*(?:%%[^%]*)*)%
| (\S+)/ixg) {
if (defined($1)) { # Keyword
my $keyword = lc($1);
if ($keyword eq "table") {
$table = new RECTable();
undef $row;
undef $cell;
} elsif ($keyword eq "row") {
if (!defined($table)) {
die "Invalid data: row without table";
}
$row = $table->addRow();
undef $cell;
} elsif ($keyword eq "cell") {
if (!defined($row)) {
die "Invalid data: cell without row";
}
$cell = $row->addCell();
} else {
die "Parser bug: unknown keyword";
}
} elsif (defined($2)) { # String
my $content = $2;
$content =~ s/%%/%/g;
if (defined($cell)) {
$cell->addContent($content);
} elsif (defined($row)) {
die "Invalid data: string after row keyword";
} elsif (defined($table)) {
$table->addCaption($content);
} else {
die "Invalid data: string before table keyword";
}
} elsif (defined($3)) { # Error
die "Invalid data: $3";
} else {
die "Parser bug: no capturing group matched";
}
}
if (!defined(table)) {
die "Invalid data: table keyword missing";
}
return table;
}</pre>
<h4>Python</h4>
<pre>def importtable(filecontents):
table = None
row = None
cell = None
for match in re.finditer(
r"""(?ix)\b(?P<keyword>table|row|cell)\b
| %(?P<string>[^%]*(?:%%[^%]*)*)%
| (?P<error>\S+)""", filecontents):
if match.group("keyword") != None:
keyword = match.group("keyword").lower()
if keyword == "table":
table = RECTable()
row = None
cell = None
elif keyword == "row":
if table == None:
raise Exception("Invalid data: row without table")
row = table.addRow()
cell = None
elif keyword == "cell":
if row == None:
raise Exception("Invalid data: cell without row")
cell = row.addCell()
else:
raise Exception("Parser bug: unknown keyword")
elif match.group("string") != None:
content = match.group("string").replace("%%", "%")
if cell != None:
cell.addContent(content)
elif row != None:
raise Exception("Invalid data: string after row keyword")
elif table != None:
table.addCaption(content)
else:
raise Exception("Invalid data: string before table keyword")
elif match.group("error") != None:
raise Exception("Invalid data: " + match.group("error"))
else:
raise Exception("Parser bug: no capturing group matched")
if table == None:
raise Exception("Invalid data: table keyword missing")
return table</pre>
<h4>PHP</h4>
<pre>function importTable($fileContents) {
preg_match_all(
'/ \b(?P<keyword>table|row|cell)\b
| (?P<string>%[^%]*(?:%%[^%]*)*%)
| (?P<error>\S+)/ix',
$fileContents, $matches, PREG_PATTERN_ORDER);
$table = NULL;
$row = NULL;
$cell = NULL;
for ($i = 0; $i < count($matches[0]); $i++) {
if ($matches['keyword'][$i] != NULL) {
$keyword = strtolower($matches['keyword'][$i]);
if ($keyword == "table") {
$table = new RECTable();
$row = NULL;
$cell = NULL;
} elseif ($keyword == "row") {
if ($table == NULL)
throw new Exception("Invalid data: row without table");
$row = $table->addRow();
$cell = NULL;
} elseif ($keyword == "cell") {
if ($row == NULL)
throw new Exception("Invalid data: cell without row");
$cell = $row->addCell();
} else {
throw new Exception("Parser bug: unknown keyword");
}
} elseif ($matches['string'][$i] != NULL) {
$content = $matches['string'][$i];
$content = substr($content, 1, strlen($content)-2);
$content = str_replace('%%', '%', $content);
if ($cell != NULL)
$cell->addContent($content);
elseif ($row != NULL)
throw new Exception("Invalid data: string after row keyword");
elseif ($table != NULL)
$table->addCaption($content);
else
throw new Exception("Invalid data: string before table keyword");
} elseif ($matches['error'][$i] != NULL) {
throw new Exception("Invalid data: " + $matches['error'][$i]);
} else {
throw new Exception("Parser bug: no capturing group matched");
}
}
if ($table == NULL)
throw new Exception("Invalid data: table keyword missing");
return $table;
}</pre>
<h4>Ruby</h4>
<pre>def importtable(filecontents)
table = nil
row = nil
cell = nil
groupkeyword = 0;
groupstring = 1;
grouperror = 2;
regexp = / \b(table|row|cell)\b
| %([^%]*(?:%%[^%]*)*)%
| (\S+)/ix
filecontents.scan(regexp) do |match|
if match[groupkeyword]
keyword = match[groupkeyword].downcase
if keyword == "table"
table = RECTable.new()
row = nil
cell = nil
elsif keyword == "row"
if table.nil?
raise "Invalid data: row without table"
end
row = table.addRow()
cell = nil
elsif keyword == "cell"
if row.nil?
raise "Invalid data: cell without row"
end
cell = row.addCell()
else
raise "Parser bug: unknown keyword"
end
elsif not match[groupstring].nil?
content = match[groupstring].gsub("%%", "%")
if not cell.nil?
cell.addContent(content)
elsif not row.nil?
raise "Invalid data: string after row keyword"
elsif not table.nil?
table.addCaption(content)
else
raise "Invalid data: string before table keyword"
end
elsif not match[grouperror].nil?
raise "Invalid data: " + match.group("error")
else
raise "Parser bug: no capturing group matched"
end
end
if table.nil?
raise "Invalid data: table keyword missing"
end
return table
end</pre>
<h3>Discussion</h3>
<pre> \b(?<keyword>table|row|cell)\b
| %(?<string>[^%]*(?:%%[^%]*)*)%
| (?<error>\S+)</pre>
<p>Regex options: Free-spacing, case insensitive<br>
Regex flavors: .NET,
Java 7, XRegExp, PCRE 7, Perl 5.10, Ruby 1.9</p>
<pre> \b(?P<keyword>table|row|cell)\b
| %(?P<string>[^%]*(?:%%[^%]*)*)%
| (?P<error>\S+)</pre>
<p>Regex options: Free-spacing, case insensitive<br>
Regex flavors: PCRE 4
and later, Perl 5.10, Python</p>
<pre> \b(table|row|cell)\b
| %([^%]*(?:%%[^%]*)*)%
| (\S+)</pre>
<p>Regex options: Free-spacing, case insensitive<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<pre>\b(table|row|cell)\b|%([^%]*+(?:%%[^%]*+)*+)%|(\S+)</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h1>4. Validation and Formatting</h1>
<h2>4.1. Validate Email Addresses</h2>
<h3>Solution</h3>
<h4>Simple</h4>
<pre>^\S+@\S+$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python</p>
<pre>\A\S+@\S+\Z</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby</p>
<h4>Simple, with restrictions on characters</h4>
<pre>^[A-Z0-9+_.-]+@[A-Z0-9.-]+$</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python</p>
<pre>\A[A-Z0-9+_.-]+@[A-Z0-9.-]+\Z</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby</p>
<h4>Simple, with all valid local part characters</h4>
<pre>^[A-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[A-Z0-9.-]+$</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python</p>
<pre>\A[A-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[A-Z0-9.-]+\Z</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby</p>
<h4>No leading, trailing, or consecutive dots</h4>
<pre>^[A-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\.[A-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[A-Z0-9-]+(?:\.[A-Z0-9-]+)*$</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python</p>
<pre>\A[A-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\.[A-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[A-Z0-9-]+(?:\.[A-Z0-9-]+)*\Z</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby</p>
<h4>Top-level domain has two to six letters</h4>
<pre>^[\w!#$%&'*+/=?`{|}~^-]+(?:\.[\w!#$%&'*+/=?`{|}~^-]+)*@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python</p>
<pre>\A[\w!#$%&'*+/=?`{|}~^-]+(?:\.[\w!#$%&'*+/=?`{|}~^-]+)*@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\Z</pre>
<p>Regex options: Case
insensitive<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby</p>
<h2>4.2. Validate and Format North American Phone Numbers</h2>
<h3>Solution</h3>
<h4>Regular expression</h4>
<pre>^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h4>Replacement</h4>
<pre>($1) $2-$3</pre>
<pre>(\1) \2-\3</pre>
<h4>C# example</h4>
<pre>Regex phoneRegex =
new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
if (phoneRegex.IsMatch(subjectString)) {
string formattedPhoneNumber =
phoneRegex.Replace(subjectString, "($1) $2-$3");
} else {
// Invalid phone number
}</pre>
<h4>JavaScript example</h4>
<pre>var phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (phoneRegex.test(subjectString)) {
var formattedPhoneNumber =
subjectString.replace(phoneRegex, "($1) $2-$3");
} else {
// Invalid phone number
}</pre>
<h3>Discussion</h3>
<pre>^ # Assert position at the beginning of the string.
\( # Match a literal "("
? # between zero and one time.
( # Capture the enclosed match to backreference 1:
[0-9] # Match a digit
{3} # exactly three times.
) # End capturing group 1.
\) # Match a literal ")"
? # between zero and one time.
[-. ] # Match one hyphen, dot, or space
? # between zero and one time.
… # [Match the remaining digits and separator.]
$ # Assert position at the end of the string.</pre>
<h3>Variations</h3>
<h4>Eliminate invalid phone numbers</h4>
<pre>^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h4>Find phone numbers in documents</h4>
<pre>\(?\b([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})\b</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h4>Allow a leading “1”</h4>
<pre>^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h4>Allow seven-digit phone numbers</h4>
<pre>^(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h2>4.3. Validate International Phone Numbers</h2>
<h3>Solution</h3>
<h4>Regular expression</h4>
<pre>^\+(?:[0-9] ?){6,14}[0-9]$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h4>JavaScript example</h4>
<pre>function validate(phone) {
var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
if (regex.test(phone)) {
// Valid international phone number
} else {
// Invalid international phone number
}
}</pre>
<h3>Discussion</h3>
<pre>^ # Assert position at the beginning of the string.
\+ # Match a literal "+" character.
(?: # Group but don't capture:
[0-9] # Match a digit.
\x20 # Match a space character
? # between zero and one time.
) # End the noncapturing group.
{6,14} # Repeat the group between 6 and 14 times.
[0-9] # Match a digit.
$ # Assert position at the end of the string.</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<h3>Variations</h3>
<h4>Validate international phone numbers in EPP format</h4>
<pre>^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h2>4.4. Validate Traditional Date Formats</h2>
<h3>Solution</h3>
<pre>^[0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^[0-3][0-9]/[0-3][0-9]/(?:[0-9][0-9])?[0-9][0-9]$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])/(?:[0-9]{2})?[0-9]{2}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(3[01]|[12][0-9]|0?[1-9])/(1[0-2]|0?[1-9])/(?:[0-9]{2})?[0-9]{2}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])/[0-9]{4}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(?:(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])|(3[01]|[12][0-9]|0?[1-9])/(1[0-2]|0?[1-9]))/(?:[0-9]{2})?[0-9]{2}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(?:
# m/d or mm/dd
(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])
|
# d/m or dd/mm
(3[01]|[12][0-9]|0?[1-9])/(1[0-2]|0?[1-9])
)
# /yy or /yyyy
/(?:[0-9]{2})?[0-9]{2}$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<pre>^(?:(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])|(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9]))/[0-9]{4}$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(?:
# mm/dd
(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])
|
# dd/mm
(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])
)
# /yyyy
/[0-9]{4}$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<h3>Variations</h3>
<pre>\b(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}\b</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h2>4.5. Validate Traditional Date Formats, Excluding Invalid Dates</h2>
<h3>Solution</h3>
<h4>C#</h4>
<pre>^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java 7, XRegExp, PCRE 7, Perl 5.10</p>
<pre>DateTime foundDate;
Match matchResult = Regex.Match(SubjectString,
"^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/" +
"(?<year>(?:[0-9]{2})?[0-9]{2})$");
if (matchResult.Success) {
int year = int.Parse(matchResult.Groups["year"].Value);
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
try {
foundDate = new DateTime(year,
int.Parse(matchResult.Groups["month"].Value),
int.Parse(matchResult.Groups["day"].Value));
} catch {
// Invalid date
}
}</pre>
<pre>^(?<day>[0-3]?[0-9])/(?<month>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java 7, XRegExp, PCRE 7, Perl 5.10</p>
<pre>DateTime foundDate;
Match matchResult = Regex.Match(SubjectString,
"^(?<day>[0-3]?[0-9])/(?<month>[0-3]?[0-9])/" +
"(?<year>(?:[0-9]{2})?[0-9]{2})$");
if (matchResult.Success) {
int year = int.Parse(matchResult.Groups["year"].Value);
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
try {
foundDate = new DateTime(year,
int.Parse(matchResult.Groups["month"].Value),
int.Parse(matchResult.Groups["day"].Value));
} catch {
// Invalid date
}
}</pre>
<h4>Perl</h4>
<pre>^([0-3]?[0-9])/([0-3]?[0-9])/((?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>@daysinmonth = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$validdate = 0;
if ($subject =~ m!^([0-3]?[0-9])/([0-3]?[0-9])/((?:[0-9]{2})?[0-9]{2})$!)
{
$month = $1;
$day = $2;
$year = $3;
$year += 2000 if $year < 50;
$year += 1900 if $year < 100;
if ($month == 2 && $year % 4 == 0 && ($year % 100 != 0 ||
$year % 400 == 0)) {
$validdate = 1 if $day >= 1 && $day <= 29;
} elsif ($month >= 1 && $month <= 12) {
$validdate = 1 if $day >= 1 && $day <= $daysinmonth[$month-1];
}
}</pre>
<pre>@daysinmonth = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$validdate = 0;
if ($subject =~ m!^([0-3]?[0-9])/([0-3]?[0-9])/((?:[0-9]{2})?[0-9]{2})$!)
{
$day = $1;
$month = $2;
$year = $3;
$year += 2000 if $year < 50;
$year += 1900 if $year < 100;
if ($month == 2 && $year % 4 == 0 && ($year % 100 != 0 ||
$year % 400 == 0)) {
$validdate = 1 if $day >= 1 && $day <= 29;
} elsif ($month >= 1 && $month <= 12) {
$validdate = 1 if $day >= 1 && $day <= $daysinmonth[$month-1];
}
}</pre>
<h4>Pure regular expression</h4>
<pre>^(?:
# February (29 days every year)
(?<month>0?2)/(?<day>[12][0-9]|0?[1-9])
|
# 30-day months
(?<month>0?[469]|11)/(?<day>30|[12][0-9]|0?[1-9])
|
# 31-day months
(?<month>0?[13578]|1[02])/(?<day>3[01]|[12][0-9]|0?[1-9])
)
# Year
/(?<year>(?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Perl 5.10, Ruby 1.9</p>
<pre>^(?:
# February (29 days every year)
(0?2)/([12][0-9]|0?[1-9])
|
# 30-day months
(0?[469]|11)/(30|[12][0-9]|0?[1-9])
|
# 31-day months
(0?[13578]|1[02])/(3[01]|[12][0-9]|0?[1-9])
)
# Year
/((?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<pre>^(?:(0?2)/([12][0-9]|0?[1-9])|(0?[469]|11)/(30|[12][0-9]|0?[1-9])|(0?[13578]|1[02])/(3[01]|[12][0-9]|0?[1-9]))/((?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(?:
# February (29 days every year)
(?<day>[12][0-9]|0?[1-9])/(?<month>0?2)
|
# 30-day months
(?<day>30|[12][0-9]|0?[1-9])/(?<month>0?[469]|11)
|
# 31-day months
(?<day>3[01]|[12][0-9]|0?[1-9])/(?<month>0?[13578]|1[02])
)
# Year
/(?<year>(?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Perl 5.10, Ruby 1.9</p>
<pre>^(?:
# February (29 days every year)
([12][0-9]|0?[1-9])/(0?2)
|
# 30-day months
(30|[12][0-9]|0?[1-9])/([469]|11)
|
# 31-day months
(3[01]|[12][0-9]|0?[1-9])/(0?[13578]|1[02])
)
# Year
/((?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Java, XRegExp, PCRE, Perl, Python, Ruby</p>
<pre>^(?:([12][0-9]|0?[1-9])/(0?2)|(30|[12][0-9]|0?[1-9])/([469]|11)|(3[01]|[12][0-9]|0?[1-9])/(0?[13578]|1[02]))/((?:[0-9]{2})?[0-9]{2})$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h3>Variations</h3>
<pre># 2 May 2007 till 29 August 2008
^(?:
# 2 May 2007 till 31 December 2007
(?:
# 2 May till 31 May
(?<day>3[01]|[12][0-9]|0?[2-9])/(?<month>0?5)/(?<year>2007)
|
# 1 June till 31 December
(?:
# 30-day months
(?<day>30|[12][0-9]|0?[1-9])/(?<month>0?[69]|11)
|
# 31-day months
(?<day>3[01]|[12][0-9]|0?[1-9])/(?<month>0?[78]|1[02])
)
/(?<year>2007)
)
|
# 1 January 2008 till 29 August 2008
(?:
# 1 August till 29 August
(?<day>[12][0-9]|0?[1-9])/(?<month>0?8)/(?<year>2008)
|
# 1 Janary till 30 June
(?:
# February
(?<day>[12][0-9]|0?[1-9])/(?<month>0?2)
|
# 30-day months
(?<day>30|[12][0-9]|0?[1-9])/(?<month>0?[46])
|
# 31-day months
(?<day>3[01]|[12][0-9]|0?[1-9])/(?<month>0?[1357])
)
/(?<year>2008)
)
)$</pre>
<p>Regex options: Free-spacing<br>
Regex flavors: .NET,
Perl 5.10, Ruby 1.9</p>
<h2>4.6. Validate Traditional Time Formats</h2>
<h3>Solution</h3>
<pre>^(1[0-2]|0?[1-9]):([0-5]?[0-9])( ?[AP]M)?$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])( ?[AP]M)?$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<h3>Variations</h3>
<pre>\b(2[0-3]|[01]?[0-9]):([0-5]?[0-9])\b</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>(?<![:\w])(2[0-3]|[01]?[0-9]):([0-5]?[0-9])(?![:\w])</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, PCRE, Perl, Python, Ruby 1.9</p>
<h2>4.7. Validate ISO 8601 Dates and Times</h2>
<h3>Solution</h3>
<h4>Dates</h4>
<pre>^([0-9]{4})-(1[0-2]|0[1-9])$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby</p>
<pre>^(?<year>[0-9]{4})-(?<month>1[0-2]|0[1-9])$</pre>
<p>Regex options: None<br>
Regex flavors: .NET,
Java 7, XRegExp, PCRE 7, Perl 5.10, Ruby 1.9</p>
<pre>^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$</pre>
<p>Regex options: None<br>
Regex flavors: PCRE,
Python</p>
<pre>^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])$</pre>
<p>Regex options: None<br>