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
类的字符串
如果要检查字符串中是否存在某些模式 ,请附加并在模式前加上“。*”。 结果将接受包含模式的字符串。
示例:假设您有一些正则表达式a(b | c) ,用于检查字符串是否与ab
或ac
匹配
.*(a(b|c)).*
将检查字符串是否包含ab
或ac
。
这种方法的一个缺点是它不会给你匹配的位置。
你可以使用string.indexOf("{item}")
来完成它。 如果结果大于-1,则{item}
在字符串中