Using java Syntax Highlighting
- StringBuffer sb = new StringBuffer();
- sb.append( "\\A" ); // Start of input
- sb.append( "content://"+URI_AUTHORITY ); // content://provider
- sb.append( "/(type1|type2|type/with/subtype)" ); // First path segment should be a recognized type (in a capture group)
- sb.append( "(?:/(\\d*))?"); // Optional second path segment should be digits (in a capture group)
- sb.append( "/?"); // Optional end path separator
- sb.append( "(?:\\?(.*))?" ); // Optional argument list (in a capture group) prefixed with '?'
- sb.append( "\\Z" ); // End of input
- Pattern regex = Pattern.compile( sb.toString(), Pattern.CASE_INSENSITIVE );
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
Why? My app's single ContentProvider supports several types, kinda like the Contacts app. This seemed easier than digging into the pre-parsed URI with lots of nested if/else statements. Using this, I can quickly check if the URI matches and pull out the informative data in a single pass. It also allowed me to be more flexible in my inputs (ending path separators, etc.).
Usage Example 1: getType(..):
Using java Syntax Highlighting
- @Override
- public String getType( Uri uri ) {
- Matcher matcher = URI_PATTERN.matcher( uri.toString() );
- String mime_type = null;
- if( matcher.matches() ) {
- String type = matcher.group( 1 ).toLowerCase();
- boolean has_ref_id = (matcher.group( 2 )!=null);
- if( "task".equals( type ) ) {
- if( has_ref_id ) {
- mime_type = MIME_TYPE_TASK;
- } else {
- mime_type = MIME_TYPE_TASKS;
- }
- } // else.. test against other types
- }
- return mime_type;
- }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
Usage Example 2: query(..):
Using java Syntax Highlighting
- @Override
- public Cursor query(
- Uri uri,
- String[] projection,
- String selection,
- String[] selectionArgs,
- String sortOrder
- ) {
- Cursor cursor = null;
- Matcher matcher = URI_PATTERN.matcher( uri.toString() );
- if( matcher.matches() ) {
- String type = matcher.group( 1 ).toLowerCase();
- String ref_id = matcher.group( 2 );
- String uri_args = matcher.group( 3 );
- if( "task".equals( type ) ) {
- cursor = queryTask( ref_id, uri_args, projection, selection, selectionArgs, sortOrder );
- } // else.. test against other types
- }
- return cursor;
- }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
One thing you might consider changing is making the reference id mutually exclusive with the selection arguments.

