Java regular expressions handle the escape of special characters

  • 2020-05-27 05:37:54
  • OfStack

A regex requires an escape character

'$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|'

Abnormal phenomena:

java.util.regex.PatternSyntaxException: Dangling meta. character '*' near index 0

The solution

Escape by adding \\ to special characters.

Note: although the use of [] is acceptable under partial conditions, the following is reported in the case of a (, [, and {range boundary initializer not matching:

Abnormal phenomenon

java.util.regex.PatternSyntaxException: Illegal repetition near index 50

The Java filter regular expression special word code is as follows (note :\\ need the first substitution, otherwise the replace method will have a logical bug)


/**
 *  Escape the regular special character   ( $()*+.[]?\^{},| ) 
 * 
 * @param keyword
 * @return
 */
public static String escapeExprSpecialWord(String keyword) {
 if (StringUtils.isNotBlank(keyword)) {
 String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
 for (String key : fbsArr) {
 if (keyword.contains(key)) {
 keyword = keyword.replace(key, "\\" + key);
 }
 }
 }
 return keyword;
}

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: