[英]Regex for finding a pattern in a string
我可以使用switchaubcsp-loafsyvgvhv
类的字符串,该字符串可能包含以下任何一种模式: s-loaf
, p-loaf
等。
以下是详细要求:
1st character - Any of [p,s,a,r,l],
2nd character -> [-], Followed by Word [loaf].
在上面的示例中,当搜索[p-loaf]
,使用java.util.regex
找到了文本p-loaf
,该文本从11索引开始到索引17结束。
查找第一个字符为Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf]
的正则表达式是什么?
[psarl]-loaf
如果您希望单词以该单词开头,则将^
添加到开头,如果您希望单词以该单词结尾,则将$
添加到结尾。
你可以在这里尝试演示正则表达式
import java.util.regex.*;
public class RegexExamples {
public static void main(String[] args) {
RegexTag("devicexyzas-loafcdbdd", "[psarl][-]loaf");
}
public static void RegexTag(Stri`enter code here`ng Content, String PatternToMatch){
Pattern pattern;
try {
pattern = Pattern.compile(PatternToMatch);
}
catch (PatternSyntaxException e)
{
System.err.println ("Regex syntax error: " + e.getMessage ());
System.err.println ("Error description: " + e.getDescription ());
System.err.println ("Error index: " + e.getIndex ());
System.err.println ("Erroneous pattern: " + e.getPattern ());
return;
}
Matcher matcher = pattern.matcher(Content);
System.out.println ("Regex = " + Content);
System.out.println ("Text = " + PatternToMatch);
System.out.println ();
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.