Update reserved words (with exceptions) using regular expressions

Viewed 55

Using this regex in Java 8, I want to update my reserved words with uppercase taking into account these restrictions:

  • Capitalize only the reserved words that are between spaces or beginning/end of sentence
  • If it is in parentheses or brackets, update it also if it is not included in a word
  • Do not update reserved words included within a word or after a hyphen

My code:

String[] RESERVED_WORDS = { "id", "url" };
String[] result = {"id report with report-id is in the url but not in the identifier (id)"};
Arrays.stream(RESERVED_WORDS).forEach(word -> result[0] = result[0].replaceAll("(\\b" + word + "\\b", word.toUpperCase()));

My result:

ID report with report-ID is in the URL but not in the identifier (id)

My expectation:

ID report with report-id is in the URL but not in the identifier (ID)

I have all exceptions handled except the one after the hyphen, any idea yo improve my code?

1 Answers

You can use

String[] RESERVED_WORDS = { "id", "url" };
String[] result = {"id report with report-id is in the url but not in the identifier (id)"};
Arrays.stream(RESERVED_WORDS).forEach(word -> result[0] = result[0].replaceAll("(?i)(?<![\\w-])" + Pattern.quote(word) + "(?![\\w-])", word.toUpperCase()));
System.out.println(result[0]); 

See the online demo, output:

ID report with report-id is in the URL but not in the identifier (ID)

The "(?i)(?<![\\w-])" + Pattern.quote(word) + "(?![\\w-])" part creates a regex like (?i)(?<![-\w])id(?![-\w]) that matches id in a case insensitive way (due to the (?i) embedded flag option) that is not preceded with a - or any word char, and is not followed by - or any word char.

Related