View Javadoc
1   /**
2    * Oshi (https://github.com/dblock/oshi)
3    * 
4    * Copyright (c) 2010 - 2015 The Oshi Project Team
5    * 
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of the Eclipse Public License v1.0
8    * which accompanies this distribution, and is available at
9    * http://www.eclipse.org/legal/epl-v10.html
10   * 
11   * Contributors:
12   * dblock[at]dblock[dot]org
13   * alessandro[at]perucchi[dot]org
14   * widdis[at]gmail[dot]com
15   * https://github.com/dblock/oshi/graphs/contributors
16   */
17  package oshi.util;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  import java.util.regex.Matcher;
22  import java.util.regex.Pattern;
23  
24  /**
25   * String parsing utility.
26   * 
27   * @author alessio.fachechi[at]gmail[dot]com
28   */
29  public abstract class ParseUtil {
30  
31  	/**
32  	 * Hertz related variables
33  	 */
34  	final private static String Hertz = "Hz";
35  	final private static String kiloHertz = "k" + Hertz;
36  	final private static String megaHertz = "M" + Hertz;
37  	final private static String gigaHertz = "G" + Hertz;
38  	final private static String teraHertz = "T" + Hertz;
39  	final private static String petaHertz = "P" + Hertz;
40  	final private static Map<String, Long> multipliers;
41  
42  	static {
43  		multipliers = new HashMap<String, Long>();
44  		multipliers.put(Hertz, 1L);
45  		multipliers.put(kiloHertz, 1000L);
46  		multipliers.put(megaHertz, 1000000L);
47  		multipliers.put(gigaHertz, 1000000000L);
48  		multipliers.put(teraHertz, 1000000000000L);
49  		multipliers.put(petaHertz, 1000000000000000L);
50  	}
51  
52  	/**
53  	 * Parse hertz from a string, eg. "2.00MHz" in 2000000L.
54  	 * 
55  	 * @param hertz
56  	 *            Hertz size.
57  	 * @return {@link Long} Hertz value or -1 if not parsable.
58  	 */
59  	public static long parseHertz(String hertz) {
60  		Pattern pattern = Pattern.compile("(\\d+(.\\d+)?) ?([kMGT]?Hz)");
61  		Matcher matcher = pattern.matcher(hertz.trim());
62  
63  		if (matcher.find() && (matcher.groupCount() == 3)) {
64  			try {
65  				Double value = Double.valueOf(matcher.group(1));
66  				String unit = matcher.group(3);
67  
68  				if (multipliers.containsKey(unit)) {
69  					value = value * multipliers.get(unit);
70  					return value.longValue();
71  				}
72  			} catch (NumberFormatException e) {
73  			}
74  		}
75  
76  		return -1L;
77  	}
78  
79  }