java - How to use Caret and dollar in regex Expression? -
i'm trying learn regex i'm struck @ first code only. read caret(^) , dollar($) used match @ beginning , end of test respectively. i'm getting hard time figure out wrong code.
public class test1 { public static void main(string[] args) { // todo auto-generated method stub string lettera="cat die"; string pattern="[^cat]"; system.out.println(lettera.matches(pattern)); string pattern1="^(cat)"; system.out.println(lettera.matches(pattern1)); string letterb="lending cat"; string pattern3="[cat$]"; system.out.println(letterb.matches(pattern3)); string pattern4="cat$"; system.out.println(letterb.matches(pattern4)); } }
every syso giving me output false
caret , dollar anchors tells if pattern should start(caret) , end(dollar) of line.
also, inside of brackets, syntax changed. if start [^...] means negation, trying match char not after caret. , $ inside brackets tells engine looking match $ char.
also, matches in java return true if match entire string.
having things in mind, lets pass each of cases , see why not matching:
string lettera="cat die"; string pattern="[^cat]";
this regex looking single char not 'c' or 'a' or 't'. string "f" return true one.
system.out.println(lettera.matches(pattern)); string pattern1="^(cat)";
the () capturing groups, nothing in case matching. ^ tells match in start of string, , regex trying match string "cat". possible match returns true case.
string letterb="lending cat"; string pattern3="[cat$]";
this trying match single char strings either 'c' or 'a' or 't' or '$'
and :
string pattern4="cat$";
is trying match string 'cat' (anchored end, doesn't make difference).
so, problem, need use .* operator matches number of chars like:
^cat.*$
(if want string starts cat)^.*cat$
(if want string ends cat)^.*cat.*$
(if want string has text cat in it)
Comments
Post a Comment