[英]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 "|"我想用java编写一个程序来检查字符串是否以特定文本开头,后跟“|”
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正则表达式应该匹配上面的所有a
, b
, c
, d
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
.你可以删除.*
如果你想使用Matcher#find
或者在Matcher#matches
情况下保留它。
Pattern.quote
generates regex which represents literal passed as argument. Pattern.quote
生成表示作为参数传递的文字的正则表达式。 For instance if your text
would be "a+b"
it would return regex equivalent to "a\\\\+b"
.例如,如果您的text
是"a+b"
它将返回等效于"a\\\\+b"
正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.