简体   繁体   English

使用多个分隔符Java分割字符串

[英]Splitting string using multiple delimiters Java

I would like to split a string using multiple delimiters. 我想使用多个定界符分割一个字符串。 Right now I am using this: String delims = "[\\\\s;.,:'!?()]"; 现在我正在使用: String delims = "[\\\\s;.,:'!?()]"; which seems to work fine for those characters, but when I try to add the - character, it yells at me. 这对于这些字符似乎效果很好,但是当我尝试添加-字符时,它对我大吼大叫。 How can I use all of these characters plus - as delimiters to split my string? 如何使用所有这些字符加上-作为分隔符来分割我的字符串? Thanks in advance! 提前致谢!

  • inside the character class has a special meaning. 人物类里面有特殊的意义。 It is usually used to select a range of characters like: [az] ... In order to match the dash alone ... either keep it in the beginning or the end 通常用于选择一系列字符,例如:[az] ...为了仅匹配破折号...请将其保留在开头或结尾

I just tried this and it worked 我只是尝试了一下,它奏效了

  String regex = "[\\s;.,:'!?()-]";
  String text = "jatin-shah-testing";

  String[] tokens = text.split(regex);
  for(int i = 0; i < tokens.length; i++)
    System.out.println(tokens[i]);

- has a special meaning in character classes, indicating ranges. -在字符类中具有特殊含义,指示范围。 (Eg [0-9] will match any digit.) (例如[0-9]将匹配任何数字。)

However, if you put if you put it either as the first character or the last it will be matched as a literal - . 但是,如果您将其放置为第一个字符或最后一个字符,则将其与文字-匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM