Archive

Posts Tagged ‘regular expression’

The use of grouping in Regular expressions

October 9, 2012 Leave a comment

I was recently asked to parse some responses coming from the CLI of a new device that were working with, instead of writing my own parser i decided to go for a different approach and use Regular expressions to my advantage.

From looking at the output, i noticed that the information is arranged like this:
Hardware revision             2.1             Board revision      M0
Serial number         4279256517            Part number        73-1539-03

As you can see, the general structure of this output is clear… but i am looking for specific data out of this mess.

This is where Regular expression grouping will help me get the information i am looking for.
In order for us to use grouping, we need to enter “()” into our expressions.
For Example:

RegExp = (Hardware revision)\\s+([0-9]+\\.[0-9]+)

This Regular expression will search for patterns that start with the words “Hardware revision” and then some spaces (but at least one), then a number with a dot for example 1.0, 4.3 etc…

If there is a match for this sort of pattern (for example “Hardware revision 2.1”) we will get a matcher that has 3 groups containing our information.
matcher.group(0) = Hardware revision 2.1
matcher.group(1) = Hardware revision
matcher.group(2) = 2.1

Consider the following:

        Pattern hwVerPattern = Pattern
				.compile("("+HW_VER_PARAMETER+")\\s+([0-9]+\\.[0-9]+)");
		Pattern serialNumberPattern = Pattern
				.compile("("+SERIAL_PARAMETER+")\\s+([0-9a-zA-Z]+)");

		List<Pattern> patterns = new LinkedList<Pattern>();
		patterns.add(hwVerPattern);
		patterns.add(serialNumberPattern);

		BufferedReader reader = new BufferedReader(new StringReader(response));
		String currentLine = null;
		Iterator<Pattern> iterator = patterns.iterator();
		try {
			while ((currentLine = reader.readLine()) != null) {
				while (iterator.hasNext()) {
					Pattern pattern = iterator.next();
					Matcher matcher = pattern.matcher(currentLine);

					if (matcher.find()) {
						assignValueToItem(matcher.group(1), matcher.group(2), item);
						iterator.remove();
					}
				}
				if (patterns.size() > 0)
					iterator = patterns.iterator();
				else
					break;
			}
		} catch (IOException e) {
			LOGGER.error("an error has occured while parsing the responce", e);
			return null;
		}