fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. test("hello's");
  13. test(";;;1235'5454!!");
  14. test(";;;1235'L454!!'");
  15. }
  16.  
  17. static void test(String input) {
  18. String regex = regex(input);
  19. String replaceInBetween = replaceInBetween(input);
  20. System.out.println("regex: " + regex);
  21. System.out.println("rib: " + replaceInBetween);
  22. System.out.println(regex.equals(replaceInBetween));
  23. }
  24.  
  25. static String regex(String substr) {
  26. substr = substr.replaceAll("([^\\p{L}\\p{N}\\p{Mn}_\\-<>'])"," $1 ");
  27. substr = substr.replaceAll("([\\p{N}\\p{L}])'(\\p{L})", "$1 '$2");
  28. substr = substr.replaceAll("([^\\p{L}])'([^\\p{L}])", "$1 ' $2");
  29. return substr;
  30. }
  31.  
  32. static String replaceInBetween(String str) {
  33. StringBuilder sb = new StringBuilder();
  34. appendInBetween(sb, str, 0, str.length());
  35. return sb.toString();
  36. }
  37.  
  38. static void appendInBetween(StringBuilder resultStr, String s, int start, int end) {
  39. for (int i = start; i < end; ++i) {
  40. char c = s.charAt(i);
  41.  
  42. // Check if c matches "([^\\p{L}\\p{N}\\p{Mn}_\\-<>'])".
  43. if (!(Character.isLetter(c)
  44. || Character.isDigit(c)
  45. || Character.getType(c) == Character.NON_SPACING_MARK
  46. || "_\\-<>'".indexOf(c) != -1)) {
  47. resultStr.append(' ');
  48. resultStr.append(c);
  49. resultStr.append(' ');
  50. } else if (c == '\'' && i > 0 && i + 1 < s.length()) {
  51. // We have a quote that's not at the beginning or end.
  52.  
  53. char b = s.charAt(i - 1);
  54. char d = s.charAt(i + 1);
  55.  
  56. if ((Character.isDigit(b) || Character.isLetter(b)) && Character.isLetter(d)) {
  57. // If the 3 chars match "([\\p{N}\\p{L}])'(\\p{L})"
  58. resultStr.append(' ');
  59. resultStr.append(c);
  60. } else if (!Character.isLetter(b) && !Character.isLetter(d)) {
  61. // If the 3 chars match "([^\\p{L}])'([^\\p{L}])"
  62. resultStr.append(' ');
  63. resultStr.append(c);
  64. resultStr.append(' ');
  65. } else {
  66. resultStr.append(c);
  67. }
  68. } else {
  69. // Everything else, just append.
  70. resultStr.append(c);
  71. }
  72. }
  73. }
  74. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
regex: hello 's
rib:   hello 's
true
regex:  ;  ;  ; 1235 ' 5454 !  ! 
rib:    ;  ;  ; 1235 ' 5454 !  ! 
true
regex:  ;  ;  ; 1235 'L454 !  ! '
rib:    ;  ;  ; 1235 'L454 !  ! '
true