简体   繁体   中英

How to use ^ (start of string) in RegExp

See my work in progress RegExp Ltd[.'s]{0,2} http://rubular.com/r/1FZvA9Nlul

I am running it against this list:

Ltd's
Ltd.
Ltd
LtdTestTEst
Ltds
sdfTestLtd

How to write a RegExp so that I don't match sdfTestLtd and LtdTestTEst , which my current RegExp matches.

To further clarify.

I pass above list through java's String.matches() method and I want it to return true only for following pattern:

Ltd's
Ltd.
Ltd
Ltds

这应该与您的示例完全匹配: ^Ltd('?s|\\.)?$

Put a ^ at the beginning, and a $ at the end.

http://rubular.com/r/F2VQUUvWLf

You should not need to.

The ^ $ special characters, to signal begin/end of string, are not usually necessary in Java, if using String.matches() or equivalent methods, because Java (contrarily to other search/match operators in other languages, and contrarily to Rubular tool) matches the full string .

   System.out.println("xHello".matches("Hello"));
   // false: no match
   System.out.println("xHello".matches(".*Hello"));
   // true: match
   System.out.println("sdfTestLtd ".matches("Ltd[.'s]{0,2}"));
   // false: no match

just put the ^ at the beginning. I think you might be confused by how the output works.

It appears print just anything you write to the Match result: window , but only matches will be highlighted.

if you want to also control the end of string, than you can use $ for that

使用此正则表达式^Ltd[.'s]{0,2}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM