Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

  • Any string
  • :
  • Any string

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading