如何用Java分隔字符,数字和符号?

时间:2019-01-15 16:43:27

标签: java

我有问题,我有一些字符串,像这样

تاپقان بولۇپ، توپلامغا 1998 – يىلىدىن 2009يىلىغىچە شىنجاڭ

是的,它们是用维吾尔语写成的,就像阿拉伯语一样,我也不知道维吾尔语。

我现在需要用空格,符号和数字将它们分开。 我用python尝试过,可以得到这个结果。

تاپقان   بولۇپ ،    توپلامغا      1998       –    يىلىدىن      2009   يىلىغىچە   شىنجاڭ

如果我忽略很多空格,那么结果就是我想要的。 而python代码是

def re_str(matched):
    replace_str = matched.group('symbol')
    return ' ' + replace_str + " "
# test is the string above
print(re.sub('(?P<symbol>\W)', re_str, re.sub('(?P<symbol>\d+)', re_str, test)))

现在的问题是:我想使用Java来达到这种效果,但是我不知道该怎么做?请帮助我

我尝试使用Java,但没有用

String pattern = "(\\d+)|([\\p{P}\\p{S}]+)|\\W";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(test);

2 个答案:

答案 0 :(得分:0)

我做了一个函数,您应该能够做到这一点,我不确定确切要使用哪个符号,因此您必须修改SYMBOL_MATCHER_REGEX以匹配您要查找的任何符号。

$ 0是对模式所找到的匹配项的引用,该函数只是用其自身替换匹配项,而是用添加前后的制表符替换。

  /**
   * The regex used to find any symbols you are looking for.
   */
  private String SYMBOL_MATCHER_REGEX = "[0-9]+";

  /**
   * A replacement which adds space before and after the match.
   */
  private String REPLACEMENT_STRING = "   $0    ";

  /** 
   * Compiled pattern for the SYMBOL_MATCHER_REGEX. 
   */
  private Pattern SYMBOL_PATTERN = Pattern.compile(SYMBOL_MATCHER_REGEX);

  public String formatUyghur(String uyghurText) {
    Matcher matcher = SYMBOL_PATTERN.matcher(uyghurText);

    return matcher.replaceAll(REPLACEMENT_STRING);
  }

答案 1 :(得分:0)

使用isAlphabeticisDigit的组合,否则您会有特殊字符。

public class Separater {

static String splitString(String str) {
    String result = "";
    int i=0;
    while (i < str.length()) {//Using while instead of for, to avoid skipping characters due to auto increment by the loop.

        if (Character.isDigit(str.charAt(i))) {
            while (i < str.length() && Character.isDigit(str.charAt(i))) {
                result += str.charAt(i);
                i++;
            }
            result += "     ";
        } else if (Character.isAlphabetic(str.charAt(i))) {
            while (i < str.length() && Character.isAlphabetic(str.charAt(i))) {
                result += str.charAt(i);
                i++;
            }
            result += "     ";
        } else {
            while (i < str.length() && !Character.isAlphabetic(str.charAt(i)) && !Character.isDigit(str.charAt(i))) {
                result += str.charAt(i);
                i++;
            }
            result += "     ";
        }
    }
    return result;
}

public static void main(String[] args) {
    System.out.println(splitString("تجاؤي#*(اىيلاؤت678345شسسصي*&&*^*!!محجذلب"));
}
}

输出 请注意,子字符串之间的间隔较大,但是SO会删除多余的空格!

  

تجاؤي#*(اىيلاؤت678345شسسصي && ^ * !!محجذلب