135*_*355 17 java string matching
我想在输入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}"
Run Code Online (Sandbox Code Playgroud)
现在我需要搜索字符串URL是否包含" /{item}/".请帮我.
这是一个例子.其实我需要检查URL是否包含匹配"/ {a-zA-Z0-9} /"的字符串
Nar*_*ala 36
你可以使用这个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");
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
这只是一个问题String.contains:
if (input.contains("{item}"))
Run Code Online (Sandbox Code Playgroud)
如果您需要知道它发生在哪里,您可以使用indexOf:
int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
...
}
Run Code Online (Sandbox Code Playgroud)
这对于匹配精确的字符串很好- 如果你需要真正的模式(例如"三个数字后跟最多2个字母AC"),那么你应该研究正则表达式.
编辑:好的,听起来你确实想要正则表达式.你可能想要这样的东西:
private static final Pattern URL_PATTERN =
Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");
...
if (URL_PATTERN.matches(input).find())
Run Code Online (Sandbox Code Playgroud)