如何基于特殊字符的subString?

时间:2015-07-09 19:02:40

标签: java

我有如下的字符串,我想获得subString如果有任何特殊字符。

 String myString="Regular $express&ions are <patterns <that can@ be %matched against *strings";

我想要像下面那样

       express
       inos
       patterns
       that
       matched
      Strings

任何人帮助我。谢谢你提前

2 个答案:

答案 0 :(得分:3)

注意: 正如@MaxZoom所指出的,似乎我没有正确理解OP的问题。 OP显然不希望将字符串拆分为特殊字符,而是保持以特殊字符开头的单词。前者对我的回答很贴切,后者是@ MaxZoom的回答。

您应该查看String.split()方法。

给它一个匹配你想要的所有字符的正则表达式,你将得到你想要的所有字符串的数组。例如:

String myString = "Regular $express&ions are <patterns <that can@ be %matched against *strings";
String[] words = myString.split("[$&<@%*]");

答案 1 :(得分:3)

此正则表达式将选择以特殊字符开头的单词:

[$&<%*](\w*)

说明:

[$&<%*] match a single character present in the list below
   $&<%* a single character in the list $&<%* literally (case sensitive)
1st Capturing group (\w*)
  \w* match any word character [a-zA-Z0-9_]
   Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
g modifier: global. All matches (don't return on first match)

DEMO

  

比赛1 [9-16] express
  比赛2 [17-21] ions
  比赛3 [27-35] patterns
  第4章[37-41] that
  第5章[51-58] matched
  比赛6 [68-75] strings

Java代码中的解决方案:

String str = "Regular $express&ions are <patterns <that can@ be %matched against *strings";
Matcher matcher = Pattern.compile("[$&<%*](\\w*)").matcher(str);
List<String> words = new ArrayList<>();
while (matcher.find()) {
  words.add(matcher.group(1));
}
System.out.println(words.toString());

// prints [express, ions, patterns, that, matched, strings]
相关问题