简体   繁体   中英

How to write a regular expression in Java to match a text at the beginning followed by a special character?

I want to write a program in java to check if a string starts with a specific text followed by a "|"

Eg

String a ="pro";
String b ="pro|100";
String c ="pro|loc";
String d ="pro|book|I'd";

String text ="pro";

String reg ="^"+text+[|]*; //this does not seem to work

The regex should match all a , b , c , d above

It looks like you may be looking for something like

String reg ="^" + Pattern.quote(text) +"($|[|].*)"; 

you can remove .* if you want to use Matcher#find or leave it in case of Matcher#matches .

Pattern.quote generates regex which represents literal passed as argument. For instance if your text would be "a+b" it would return regex equivalent to "a\\\\+b" .

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