繁体   English   中英

如何在Java中编写正则表达式以匹配开头后跟特殊字符的文本?

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

我想用java编写一个程序来检查字符串是否以特定文本开头,后跟“|”

例如

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

正则表达式应该匹配上面的所有a , b , c , d

看起来您可能正在寻找类似的东西

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

你可以删除.*如果你想使用Matcher#find或者在Matcher#matches情况下保留它。

Pattern.quote生成表示作为参数传递的文字的正则表达式。 例如,如果您的text"a+b"它将返回等效"a\\\\+b"正则表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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