Returns a string that quotes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text. For example, quoteMeta("[foo]").equals("\\[foo\\]").
(String s)
| 493 | * {@code quoteMeta("[foo]").equals("\\[foo\\]")}. |
| 494 | */ |
| 495 | static String quoteMeta(String s) { |
| 496 | StringBuilder b = new StringBuilder(2 * s.length()); |
| 497 | // A char loop is correct because all metacharacters fit in one UTF-16 code. |
| 498 | for (int i = 0, len = s.length(); i < len; i++) { |
| 499 | char c = s.charAt(i); |
| 500 | if ("\\.+*?()|[]{}^$".indexOf(c) >= 0) { |
| 501 | b.append('\\'); |
| 502 | } |
| 503 | b.append(c); |
| 504 | } |
| 505 | return b.toString(); |
| 506 | } |
| 507 | |
| 508 | // The number of capture values in the program may correspond |
| 509 | // to fewer capturing expressions than are in the regexp. |