【问题标题】:Extract words starting with a particular character from a string从字符串中提取以特定字符开头的单词
【发布时间】:2015-04-03 08:52:21
【问题描述】:

我得到以下字符串:

 String line = "#food was testy. #drink lots of. #night was fab. #three #four";

我想从中获取#food#drink#night#three#four

我试过这段代码:

    String[] words = line.split("#");
    for (String word: words) {
        System.out.println(word);
    }

但它给出了food was testydrink lots ofnigth was fabthreefour

【问题讨论】:

  • 你为什么要这样尝试。你知道字符是“#”。所以 System.out.println("#"+word);

标签: java string extraction


【解决方案1】:

split 只会在找到 # 的位置剪切整个字符串。这解释了你目前的结果。

您可能想要提取每个字符串的第一个单词,但执行任务的好工具是RegEx

这里是如何实现的:

String line = "#food was testy. #drink lots of. #night was fab. #three #four";

Pattern pattern = Pattern.compile("#\\w+");

Matcher matcher = pattern.matcher(line);
while (matcher.find())
{
    System.out.println(matcher.group());
}

输出是:

#food
#drink
#night
#three
#four

魔法发生在“#\w+”中。

所以我们搜索以# 开头的内容,后跟一个或多个字母、数字或下划线。

因为Escape Sequences,我们使用'\\' 表示'\'。

你可以玩here

findgroup解释here

  • find 方法扫描输入序列,寻找与模式匹配的下一个子序列。
  • group() 返回上一个匹配匹配的输入子序列。

[编辑]

如果您需要检测重音字符或非拉丁字符,使用\w 可能会成为问题。

例如在:

“Bonjour mon #bébé #chat。”

比赛将是:

  • #b
  • #chat

这取决于您将尽可能接受的hashTag。但这是另一个问题,multiplediscussionsexistabout it

例如,如果您想要来自任何语言的任何字符,#\p{L}+ 看起来不错,但下划线不在其中...

【讨论】:

  • 这工作正常。但是我怎样才能得到变量中的匹配词呢?
  • 字符串 mtch=matcher.group().toString();用这个得到它。 :) 十分感谢。你们俩。 @Orace 和 @Jitesh Ji。
  • 您不需要toString,因为group() 的结果已经是一个字符串。此外,您有多个结果,您可能需要使用容器将它们全部放入其中。我将编辑我的代码。
  • 你说 \w 匹配任何字母,而不是为什么它直到空格之后才运行。?
  • 我有一个数组列表,所以我可以像这样添加 tag_list.add(matcher.group()) 吗?如果我提取将在什么时候为每个工作?因为我必须将匹配的单词放在 Sqlite 中。所以我需要这样做吗?
【解决方案2】:

请按照程序去做 ==>

   String candidate = "#food was testy. #drink lots of. #night was fab. #three #four";

        String regex = "#\\w+";
        Pattern p = Pattern.compile(regex);

        Matcher m = p.matcher(candidate);
        String val = null;

        System.out.println("INPUT: " + candidate);

        System.out.println("REGEX: " + regex + "\r\n");

        while (m.find()) {
          val = m.group();
          System.out.println("MATCH: " + val);
        }
        if (val == null) {
          System.out.println("NO MATCHES: ");
        }

当我在我的 netbeans IDE 解决问题并测试程序时,它会给出如下输出

INPUT: #food was testy. #drink lots of. #night was fab. #three #four

REGEX: #\w+

MATCH: #food

MATCH: #drink

MATCH: #night

MATCH: #three

MATCH: #four

您将需要以下导入

import java.util.regex.Matcher;
import java.util.regex.Pattern;

【讨论】:

  • 您将在单词后包含空格并匹配空的# (有一个空格)。
  • 是的,你是对的,正在编辑答案。 :)
  • 你仍然匹配#
最近更新 更多