Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I avoid the implicit "^" and "$" in Java regular expression matching?
    primarykey
    data
    text
    <p>I've been struggling with doing some relatively straightforward regular expression matching in Java 1.4.2. I'm much more comfortable with the Perl way of doing things. Here's what's going on:</p> <p>I am attempting to match /^&lt;foo&gt;/ from "&lt;foo&gt;&lt;bar&gt;"</p> <p>I try:</p> <pre><code>Pattern myPattern= Pattern.compile("^&lt;foo&gt;"); Matcher myMatcher= myPattern.matcher("&lt;foo&gt;&lt;bar&gt;"); System.out.println(myMatcher.matches()); </code></pre> <p>And I get "false"</p> <p>I am used to saying:</p> <pre><code>print "&lt;foo&gt;&lt;bar&gt;" =~ /^&lt;foo&gt;/; </code></pre> <p>which does indeed return true.</p> <p>After much searching and experimentation, I discovered <a href="http://book.javanb.com/java-regular-expressions-taming-the-java-util-regex-engine/LiB0055.html" rel="nofollow noreferrer"> this</a> which said:</p> <p>"The String method further optimizes its search criteria by placing an invisible ^ before the pattern and a $ after it."</p> <p>When I tried:</p> <pre><code>Pattern myPattern= Pattern.compile("^&lt;foo&gt;.*"); Matcher myMatcher= myPattern.matcher("&lt;foo&gt;&lt;bar&gt;"); System.out.println(myMatcher.matches()); </code></pre> <p>then it returns the expected true. I do not want that pattern though. The terminating .* should not be necessary.</p> <p>Then I discovered the Matcher.useAnchoringBounds(boolean) method. I thought that expressly telling it to not use the anchoring bounds would work. It did not. I tried issuing a</p> <pre><code>myMatcher.reset(); </code></pre> <p>in case I needed to flush it after turning the attribute off. No luck. Subsequently calling .matches() still returns false.</p> <p>What have I overlooked?</p> <p>Edit: Well, that was easy, thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload