Home > Uncategorized > The use of grouping in Regular expressions

The use of grouping in Regular expressions

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
		Pattern serialNumberPattern = Pattern

		List<Pattern> patterns = new LinkedList<Pattern>();

		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);
				if (patterns.size() > 0)
					iterator = patterns.iterator();
		} catch (IOException e) {
			LOGGER.error("an error has occured while parsing the responce", e);
			return null;

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: