Created
June 19, 2022 10:54
-
-
Save bennadel/450ee451f4a1bb840434b26b2c773f55 to your computer and use it in GitHub Desktop.
Adding jreExtract() To Pluck Captured Groups Using Regular Expression 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> | |
jre = new JRegEx(); | |
// The following pattern uses a VERBOSE Regular Expression flag to allow for comments | |
// and whitespace to make the pattern easier to read. This pattern attempts to capture | |
// the aspects of an HTTP URL. | |
pattern = "(?x)^ | |
## Protocol extraction. | |
( https?:// | // )? | |
## Hostname extraction. | |
( [^./][^/\##?]+ )? | |
## Pathname extraction (must start with `./` or `/`). | |
( \./[^?\##]* | /[^?\##]* )? | |
## Query-string extraction (`?` is not captured). | |
(?: \? ( [^\##]* ) )? | |
## Fragment extraction (`##` is not captured). | |
(?: \## ( .* ) )? | |
"; | |
extractGroups( "/index.htm" ); | |
extractGroups( "./index.htm" ); | |
extractGroups( "www.bennadel.com" ); | |
extractGroups( "//www.bennadel.com/index.htm" ); | |
extractGroups( "https://www.bennadel.com##cool-beans" ); | |
extractGroups( "https://www.bennadel.com/about/about-ben-nadel.htm?source=Google##h1" ); | |
// ------------------------------------------------------------------------------- // | |
// ------------------------------------------------------------------------------- // | |
/** | |
* I apply the Java Regular Expression to the given target text using the jreExtract() | |
* method. The captured groups are mapped to human-friendly names for the demo dump. | |
*/ | |
public void function extractGroups( required string targetText ) { | |
var extraction = jre.jreExtract( targetText, pattern ); | |
dump( | |
label = "Input: #targetText#", | |
var = [ | |
match: extraction[ 0 ], | |
protocol: extraction[ 1 ], | |
hostname: extraction[ 2 ], | |
pathname: extraction[ 3 ], | |
queryString: extraction[ 4 ], | |
fragment: extraction[ 5 ] | |
] | |
); | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment