[英]Using a regex in Java to match any two strings with a colon between them
Why does this regex not match the test string?为什么这个正则表达式与测试字符串不匹配?
final String FULLY_QUALIFIED_NAME_REGEXP = "\\w+[:]\\w+";
String key = "TablePageMultipleWithServerSideFiltering:filter-1";
boolean matches = key.matches(FULLY_QUALIFIED_NAME_REGEXP);
System.out.println(matches); // false
What regex would capture:正则表达式会捕获什么:
? ?
A dash (-) isn't covered by \w
, and matches attempts to match the entire thing , succeeding only if the entire string actually matches.破折号 (-) 不被
\w
覆盖,并且匹配尝试匹配整个 thing ,只有当整个字符串实际匹配时才会成功。 Therefore, this doesn't work: The entire string doesn't match due to the dash.因此,这不起作用:由于破折号,整个字符串不匹配。
If you intended that and the only problem is that you meant for -
to also be part of the name, then use eg [a-zA-Z0-9-]
instead of \w
for that part.如果您打算这样做并且唯一的问题是您的意思是
-
也是名称的一部分,那么使用例如[a-zA-Z0-9-]
而不是\w
作为该部分。
If instead you really meant: anything that isn't a colon counts, spaces, emojis, dollars, whatever - then matching on a regexp can still be done, using [^:]+
instead (that's: "Anything that isnt a colon" in regex), but really, isn't it just a ton easier to split?相反,如果您的意思是:任何不是冒号的东西,空格,表情符号,美元,等等 - 那么仍然可以使用
[^:]+
来匹配正则表达式(即:“任何不是冒号的东西”在正则表达式中),但实际上,它不是更容易拆分吗?
NB: Surrounding the colon with []
doesn't do anything.注意:用
[]
包围冒号不会做任何事情。 Just write :
, simpler.只需写
:
,更简单。
String[] parts = "TablePageMultipleWithServerSideFiltering:filter-1".split(":", 2);
if (parts.length == 1) {
// it wasn't a match; no colon in there
} else {
String key = parts[0];
String value = parts[1];
assert key.equals("TablePageMultipleWithServerSideFiltering");
assert value.equals("filter-1");
}
Or, even simpler, if your only intent is to end up with a boolean
value that indicates: "Did the input contain a colon", forget all that and just do input.contains(":")
.或者,甚至更简单,如果您的唯一意图是最终得到一个
boolean
值,该值指示:“输入是否包含冒号”,忘记所有这些,只需执行input.contains(":")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.