tania
tania

Reputation: 1086

Regexp to match exactly one word in the beginning of the String in Java

stuck with the way regexp works in java... Why in Java regexp pattern

(\\w+)(\\s{1})is not (\\w+)

matches both:

mary is not tall
mary ann is not tall

How do I change the patter to restrict the name to appear just once, e.g. what i want is:

name+ " "+"is"+" "+"not"+" "+"tall"

Upvotes: 1

Views: 625

Answers (1)

stema
stema

Reputation: 92976

You are just missing an anchor at the start.

^(\\w+)\\sis not (\\w+)

See it here at Regexr.

^ is anchoring the regex to the start of the string. If you don't do this it will match on the string "mary ann is not tall", but from "ann" on "mary ann is not tall"

Upvotes: 5

Related Questions