Home > OS >  Using a regex in Java to match any two strings with a colon between them
Using a regex in Java to match any two strings with a colon between them

Time:12-15

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:

  • Any string
  • :
  • Any string

?

CodePudding user response:

A dash (-) isn't covered by \w, and matches attempts to match the entire thing, succeeding only if the entire string actually matches. 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 e.g. [a-zA-Z0-9-] instead of \w for that part.

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(":").

  • Related