Java 中的字符串模式匹配
我想在输入字符串中搜索给定的字符串模式。
对于例如。
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}/”的字符串
I want to search for a given string pattern in an input sting.
For 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}"
Now I need to search whether the string URL contains "/{item}/
". Please help me.
This is an example. Actually I need is check whether the URL contains a string matching "/{a-zA-Z0-9}/"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
Pattern
类来实现此目的。如果您只想匹配{}
内的单词字符,则可以使用以下正则表达式。\w
是[a-zA-Z0-9_]
的简写。如果您同意_
,则使用\w
或使用[a-zA-Z0-9]
。You can use the
Pattern
class for this. If you want to match only word characters inside the{}
then you can use the following regex.\w
is a shorthand for[a-zA-Z0-9_]
. If you are ok with_
then use\w
or else use[a-zA-Z0-9]
.这只是
String.contains
:如果你需要知道它发生在哪里,你可以使用
indexOf
:这样就可以匹配精确字符串 - 如果您需要真正的模式(例如“三位数字后跟最多 2 个字母 AC”),那么您应该查看 正则表达式。
编辑:好的,听起来您确实想要正则表达式。你可能想要这样的东西:
That's just a matter of
String.contains
:If you need to know where it occurs, you can use
indexOf
:That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.
EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:
如果你想检查某个字符串是否存在于另一个字符串中,请使用类似
String.contains
如果你想检查某个 pattern 是否存在于字符串中,请附加和在模式前面添加“.*”。结果将接受包含该模式的字符串。
示例:假设您有一些正则表达式 a(b|c) 来检查字符串是否匹配
ab
或ac
.*(a(b|c)).*
将检查字符串是否包含ab
或ac
。这种方法的缺点是它不会给你匹配的位置,如果你需要匹配的位置,你可以使用 java.util.Mather.find() 。
If you want to check if some string is present in another string, use something like
String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches
ab
orac
.*(a(b|c)).*
will check if a string contains aab
orac
.A disadvantage of this method is that it will not give you the location of the match, you can use java.util.Mather.find() if you need the position of the match.
您可以使用
string.indexOf("{item}")
来完成此操作。如果结果大于-1{item}
在字符串中You can do it using
string.indexOf("{item}")
. If the result is greater than -1{item}
is in the string