简体   繁体   English

Java 中的正则表达式 - 解析字符串数组

[英]Regex in Java - parsing a string array

I have a string array like this:我有一个这样的字符串数组:

    String tweetString = ExudeData.getInstance().filterStoppingsKeepDuplicates(tweets.text);
    // get array of words and split
    String[] wordArray = tweetString.split(" ");

After I split the array, I print the following:拆分数组后,我打印以下内容:

System.out.println(Arrays.toString(wordArray));

And the output I get is:我得到的输出是:

[new, single, fallin, dropping, days, artwork, hueshq, production, iseedaviddrums, amp, bigearl7, mix, reallygoldsmith, https, , , t, co, dk5xl4cicm, https, , , t, co, rvqkum0dk7]

What I want is to remove all the instances of commas, https, and single letters like 't' (after using split method above).我想要的是删除所有的逗号、https 和像 't' 这样的单个字母的实例(在使用上面的split方法之后)。 So I want to end up with this:所以我想以这样的方式结束:

[new, single, fallin, dropping, days, artwork, hueshq, production, iseedaviddrums, amp, bigearl7, mix, reallygoldsmith, co, dk5xl4cicm, https, co, rvqkum0dk7]

I've tried doing replaceAll like this:我试过像这样做 replaceAll:

String sanitizedString = wordArray.replaceAll("\\s+", " ").replaceAll(",+", ",");

But that just gave me the same initial output with no changes.但这只是给了我相同的初始输出,没有任何变化。 Any ideas?有任何想法吗?

If you are using Java 8如果您使用的是 Java 8

String[] result = Arrays.stream(tweetString.split("\\s+"))
            .filter(s -> !s.isEmpty())
            .toArray(String[]::new);

What I want is to remove all the instances of commas, https, and single letters like 't'我想要的是删除逗号、https 和单个字母(如“t”)的所有实例

In this case you can make multiple filters like @Andronicus do or with matches and some regex like so :在这种情况下,您可以制作多个过滤器,例如@Andronicus 或使用匹配项和一些正则表达式,如下所示:

String[] result = Arrays.stream(tweetString.split("\\s+"))
            .filter(s -> !s.matches("https|.|\\s+"))
            .toArray(String[]::new);

You can do something like this:你可以这样做:

String[] filtered = Arrays
    .stream(tweetString.split("[ ,]"))
    .filter(str -> str.length() > 1)
    .filter(str -> !str.equals("http"))

Based on my comment here is quick solution.根据我的评论,这里是快速解决方案。 (Enhance the regex with all your keywords) (使用所有关键字增强正则表达式)

 private static void replaceFromRegex(final String text ) {
    String result = text.replaceAll("https($|\\s)| (?<!\\S)[^ ](?!\\S)","");
      System.out.println(result);
  }

and then test然后测试

  public static void main(String []args) throws Exception{
      replaceFromRegex("new single fallin dropping, , https");
     }

Note: This is just sample and you will have to enhance regex to consider starting word (eg string starting with https and then space, etc)注意:这只是示例,您必须增强正则表达式以考虑起始词(例如以 https 开头的字符串,然后是空格等)

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

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