/* * [SortPrices.java] * * Summary: Sort prices embedded in chunks of text. * * Copyright: (c) 2014-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2014-04-30 initial version */ package com.mindprod.sortcode; import com.mindprod.common18.ST; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Sort prices embedded in chunks of text. *

* compare two blocks of text, each containingia price embedded in there somewhere in the form * $1.49 or $1,49 it usually followed by a space or < but anything other that $0-9. will do. * If there are two prices, the first is taken. If there are zero prices, * the item is treated as having a zero price. Malformed prices are ignored. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2014-04-30 initial version * @since 2014-04-30 */ public class SortPrices implements Comparator { /** * look for $1.48 or $1,399.99 . can be in {}. Will find on Insert. */ private static final Pattern PRICE_GRABBER = Pattern.compile( "\\$([0-9\\.,]+)" ); private static double computeKey( String s ) { final Matcher m = PRICE_GRABBER.matcher( s ); while ( m.find() ) { // found candidate final String priceString = m.group( 1 ); if ( ST.isEmpty( priceString ) ) { // null hit return 0.00d; } else { final String clean = ST.stripNaughtyCharacters( priceString, "+," ); try { return Double.parseDouble( clean ); } catch ( NumberFormatException e ) { // false hit. Keep looking continue; } } } // end while // looped but found nothing return 0.00d; } // /method /** * Compare two String Objects each containing prices * * @param a first String to compare * @param b second String to compare * * @return +ve if a>b, 0 if a==b, -ve if a<b */ public final int compare( String a, String b ) { return Double.compare( computeKey( a ), computeKey( b ) ); } // /methods } // end class