Created
June 20, 2022 10:47
-
-
Save bennadel/e61f67b2a9ea31212932c1d229aab2d1 to your computer and use it in GitHub Desktop.
Playing With Java Pattern's Named Capture Groups In ColdFusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
// The following pattern uses a VERBOSE Regular Expression flag to allow for comments | |
// and whitespace to make the pattern easier to read. In this case, we're attempting | |
// to extract parts of an email address using NAMED CAPTURE GROUPS. | |
pattern = "(?x)^ | |
(?<user> [^+@]+ ) | |
( | |
\+ (?<hash> [^@]+ ) | |
)? | |
@ | |
(?<domain> .+ ) | |
"; | |
extractEmail( "jane.doe@example.com" ) | |
extractEmail( "jane.doe+spam@example.com" ) | |
extractEmail( "j.a.n.e.d.o.e@example.com" ) | |
// ------------------------------------------------------------------------------- // | |
// ------------------------------------------------------------------------------- // | |
/** | |
* I match the Java Regular Expression pattern against the given input and then output | |
* the NAMED CAPTURE GROUPS. | |
*/ | |
public void function extractEmail( required string input ) { | |
var matcher = createObject( "java", "java.util.regex.Pattern" ) | |
.compile( pattern ) | |
.matcher( input ) | |
; | |
while ( matcher.find() ) { | |
// NOTE: With named capture groups, the Java Pattern Matcher exposes a way for | |
// us to access each group by name; but, I don't see any way to use reflection | |
// to get the list of named groups - only the number of captured groups. | |
dump( | |
label = "Input: #input#", | |
var = [ | |
"user": matcher.group( "user" ) , | |
"hash": matcher.group( "hash" ), | |
"domain": matcher.group( "domain" ) | |
] | |
); | |
} | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment