Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created June 19, 2022 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennadel/450ee451f4a1bb840434b26b2c773f55 to your computer and use it in GitHub Desktop.
Save bennadel/450ee451f4a1bb840434b26b2c773f55 to your computer and use it in GitHub Desktop.
Adding jreExtract() To Pluck Captured Groups Using Regular Expression In ColdFusion
<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