Skip to content


Java and Regex – By Example

Going to quickly outline how to use Regex in Java by example. We are trying to parse the following content to extract underlined content into different variables for each line, while ignoring comment lines:

;MATFile=align_merge.mat
;this is a comment
;labeled data
AAA=[14762.800000 14778.793750]
BBB=[16400.800000 16477.793750]
CCC=[18240.800000 18403.793750]

Regex:

^(?!\;)(.+?)\=\[([0-9.]+)\ ([0-9.]+)\]

  • ^(?!\;) – Line does not start with ; (?! is the negate operator)
  • (.+?)\= – Lazy match all characters before the = sign
  • \[([0-9.]+)\ ([0-9.]+)\] capture the two groups of 0-9 and decimal point (where applicable)
Java code fragments:

private Pattern regexLabel = Pattern.compile("^(?!\\;)(.+?)\\=\\[([0-9.]+)\\ ([0-9.]+)\\]");

Matcher m = regexLabel.matcher(line);
if (m.matches()) {
    String label = m.group(1);
    Double start= new Double(m.group(2));
    Double end = new Double(m.group(3));
  • Nothing really major, other than group 0 is always the whole matched string

Posted in Java. Tagged with , , .