[英]Regex for finding a pattern in a string
I can have string like switchaubcsp-loafsyvgvhv
which can possibly contain any of the following patterns: s-loaf
, p-loaf
etc. 我可以使用
switchaubcsp-loafsyvgvhv
类的字符串,该字符串可能包含以下任何一种模式: s-loaf
, p-loaf
等。
Following is the requirement in detail: 以下是详细要求:
1st character - Any of [p,s,a,r,l],
2nd character -> [-], Followed by Word [loaf].
In the above example, when searched for [p-loaf]
, Found the text p-loaf
starting at 11 index and ending at index 17 using java.util.regex
. 在上面的示例中,当搜索
[p-loaf]
,使用java.util.regex
找到了文本p-loaf
,该文本从11索引开始到索引17结束。
What will be the regular expression for finding the first character to be Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf]
. 查找第一个字符为
Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf]
的正则表达式是什么?
[psarl]-loaf
if you want the word to start with it, add ^
to the beginning and if you want the word to end with it, add $
to the end. [psarl]-loaf
如果您希望单词以该单词开头,则将^
添加到开头,如果您希望单词以该单词结尾,则将$
添加到结尾。
you can try it out here demo regex 你可以在这里尝试演示正则表达式
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.