[英]String Pattern Matching In Java
我想在输入sting中搜索给定的字符串模式。
对于Eg。
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}"
现在我需要搜索字符串URL是否包含“ /{item}/
”。 请帮我。
这是一个例子。 其实我需要检查URL是否包含匹配“/ {a-zA-Z0-9} /”的字符串
您可以使用Pattern
类。 如果您只想匹配{}
内的单词字符,那么您可以使用以下正则表达式。 \\w
是[a-zA-Z0-9_]
的简写。 如果你对_
好,那么使用\\w
或者使用[a-zA-Z0-9]
。
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
这只是String.contains
:
if (input.contains("{item}"))
如果你需要知道它在哪里发生,你可以使用indexOf
:
int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
...
}
这对于匹配精确的字符串很好 - 如果你需要真正的模式 (例如“三个数字后跟最多2个字母AC”),那么你应该研究正则表达式 。
编辑:好的,听起来你确实想要正则表达式。 你可能想要这样的东西:
private static final Pattern URL_PATTERN =
Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");
...
if (URL_PATTERN.matches(input).find())
如果要检查另一个字符串中是否存在某个字符串,请使用String.contains
类的字符串
is present in a string, append and prepend the pattern with '.*'. 如果要检查字符串中是否存在某些 ,请附加并添加“。*”前缀。 结果将接受包含模式的字符串。
that checks if a string matches ab
or ac
示例:假设您有一些正则表达式 ,用于检查字符串是否与ab
或ac
匹配
.*(a(b|c)).*
将检查字符串是否包含ab
或ac
。
这种方法的一个缺点是它不会给你匹配的位置。
你可以使用string.indexOf("{item}")
来完成它。 如果结果大于-1 {item}
在字符串中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.