XML technologies / Regular expressions / Java / The Matcher object / The matcher's region

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

Since Java 1.5, matchers accept a region restricting searches within the subject. It defaults to the whole subject and is changed with region.

This example reports HTML IMG tags lacking ALT attributes. Two independent matchers search the same HTML, one for IMG tags and one for ALT attributes.

They share the subject but remain independent. We explicitly restrict the ALT search to each found IMG tag, using start and end to define a region respected by find.

Isolating the whole IMG ensures ALT is sought inside it rather than elsewhere in the HTML.

// Matcher für ein IMG-Tag. Die Variable 'html' enthält den zu untersuchenden HTML-Code.
Matcher mImg = Pattern.compile("(?id)<IMG\\s+(.*?)/?>").matcher(html);

// Matcher für ein ALT-Attribut (wird auf ein IMG-Tag innerhalb der 'html'-Variable angesetzt).
Matcher mAlt = Pattern.compile("(?ix)\\b ALT \\s* =").matcher(html);

// Für alle IMG-Tags im HTML-Code ...
while (mImg.find()) {
   // Region für die ALT-Suche auf den eben gefundenen Treffer beschränken.
   mAlt.region( mImg.start(1), mImg.end(1) );

   // Komplettes IMG-Tag ausgeben, wenn darin kein ALT-Attribut gefunden wurde.
   if (! mAlt.find())
       System.out.println("Kein ALT-Attribut in: " + mImg.group());
}

Specifying the subject when constructing the mAlt matcher and the region later with mAlt.region may seem odd. Instead create the mAlt object with an empty string, supplying HTML when setting the region: mAlt.reset(html).region(...). The extra call to reset costs a little efficiency but clarifies the code.

Without restricting the ALT matcher, any occurrence of ›ALT=‹ anywhere could hide missing ALT attributes.

Add line numbers by counting newlines from the HTML start to the match start. New code is highlighted:

// Matcher für ein IMG-Tag. Die Variable 'html' enthält den zu untersuchenden HTML-Code.
Matcher mImg = Pattern.compile("(?id)<IMG\\s+(.*?)/?>").matcher(html);

// Matcher für ein ALT-Attribut (wird auf ein IMG-Tag innerhalb der 'html'-Variable angesetzt).
Matcher mAlt = Pattern.compile("(?ix)\\b ALT \\s* =").matcher(html);

// Matcher für ein Newline.
Matcher mLine = Pattern.compile("\\n").matcher(html);

// Für alle IMG-Tags im HTML-Code ...
while (mImg.find())
{
   // Region für die ALT-Suche auf den eben gefundenen Treffer beschränken.
   mAlt.region( mImg.start(1), mImg.end(1) );
   // Komplettes IMG-Tag ausgeben, wenn darin kein ALT-Attribut gefunden wurde.
   if (! mAlt.find()) {
      // Die Region zum Zählen von Newlines reicht bis zum Anfang des IMG-Tags.
      mLine.region(0, mImg.start());

      int lineNum = 1;     // Erste Zeile ist Nr. 1.
      while (mLine.find())
              lineNum++;   // Hinaufzählen.
      System.out.println("Fehlendes ALT-Attribut auf Zeile " + lineNum);
   }
}

As before, start(1) sets the ALT region inside IMG. For newline counting use start(), the position where the entire IMG tag starts, up to which newlines must be counted.

 

Points to remember

Some search methods ignore the region and reset it to the whole subject via reset .

  • Methods respecting the region:

    matches lookingAt find() (no-argument version only)

  • Methods resetting the matcher and region:

    find(text) (one-argument version)
    replaceAll replaceFirst reset (trivially)

Match offsets returned by start and end always refer to the full subject's beginning, not the region's.

 

Setting and querying region bounds

Three matcher methods manage region bounds:

 

Matcher region(int start, int ende)

This sets region start and end to positions start and ende relative to the subject's beginning. It resets the matcher and sets the match pointer to the region's start, where the next find starts.

The region lasts until the next reset call, explicit or through a method internally invoking reset (see Other matcher methods).

Returns the matcher itself, permitting method chaining (see Method chaining).

If start or ende is outside the subject or start exceeds ende , it throws IndexOutOfBoundsException .

 

int regionStart()

Returns the region's start character offset, defaulting to 0.

 

int regionEnd()

Returns the region's end character offset, defaulting to subject length.

The region method requires both start and ende even to change one bound. The table shows how.

 

Table: setting one region bound.

Region start

Region end

Java code

explicitly set

unchanged

m.region(start, m.regionEnd());

unchanged

explicitly set

m.region(m.regionStart(), end);

explicitly set

reset to default

m.reset().region(start, m.regionEnd());

reset to default

explicitly set

m.region(0, end);

 

Looking beyond the region

Restricting the region normally hides all outside text from the regex engine. For example, ˹^˼ matches the region's start even if it is not the subject's start.

Some features can see beyond it. Enable transparent bounds and disable anchoring bounds to make bounds transparent to lookahead, lookbehind, and word boundaries.

Their purpose depends on why regions are used. Earlier examples needed neither anchors nor lookahead.

Suppose a CharBuffer object holds editor text. Find-and-replace should start at the cursor, so set a region from there to the end. Suppose the cursor is here:

Madagas▵car is much too large to see on foot, so you'll need a car.

Replace every ˹\bcar\b˼ with automobile. With the region to the cursor's right, a match unexpectedly appears at its start, in ›Madagascar‹, because transparent bounds is disabled and ˹\b˼ matches the search area's start. Enabling transparent bounds exposes the preceding ›s‹ before c, so ˹\b˼ no longer matches.

 

Transparent region bounds

These methods concern transparent bounds:

 

Matcher useTransparentBounds(boolean b)

Toggles the transparent bounds option, defaulting to off or false.

Returns the matcher itself for chaining (see Method chaining).

 

boolean hasTransparentBounds()

Returns the value of transparent bounds .

Transparent bounds are off by default, hiding outside text from look constructs. (Note: I reported a bug in Java 1.5 Update 7: the regex ˹^˼ with Pattern.MULTILINE matches the region start after a newline even with both transparent and anchoring bounds off. Translator's note: still present in Java 1.6 Update 1.) Thus, ˹\b˼ can match midword because preceding letters are hidden.

The default, disabled transparent bounds behavior gives:

String regex = "\\bcar\\b"; // \bcar\b
String text  = "Madagascar is best seen by car or bike.";
Matcher m = Pattern.compile(regex).matcher(text);
m.region(7, text.length());
m.find();
System.out.println("Treffer beginnend bei " + m.start());

This prints:

Treffer beginnend bei 7

The word boundary matched inside Madagas▵car, where none exists: opaque bounds created an apparent boundary.

Enable it before calling find :

m.useTransparentBounds(true);

Then:

Treffer beginnend bei 27

Transparent bounds reveal a preceding letter, ›s‹, preventing ˹\b˼ at that position. The match occurs later, at ›...by●car●or●bike‹.

The option transparent bounds matters only when subject and region bounds differ. The reset method does not reset this option.

 

Anchoring bounds

These methods concern anchoring bounds:

 

Matcher useAnchoringBounds(boolean b)

Toggles anchoring bounds, defaulting to on or true.

Returns the matcher itself for chaining (see Method chaining).

 

boolean hasAnchoringBounds()

Returns the value of anchoring bounds.

Anchoring bounds default to on: line anchors (^ \A $ \z \Z) match region boundaries. With false , they refer only to full-subject boundaries and match only where those coincide with the region.

Disable anchoring bounds for the same reason as enabling transparency: preserve the cursor's actual textual context.

Like transparency, anchoring bounds matter only for nondefault regions. The reset method does not reset it.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top