【问题标题】:Extract a specific word from a text in java从java中的文本中提取特定单词
【发布时间】:2017-11-07 09:48:19
【问题描述】:

我想使用Java 从文本中提取特定单词。有没有可能

例如:

String str = "this is 009876 birthday of mine";

我想从Java 的上述文本中获取“009876”。这可能吗 ?

【问题讨论】:

  • 你听说过正则表达式吗?
  • 简单,做吧:String result = "009876";
  • 如果你知道这个词很容易,否则如果你一直在寻找一个数字检查regex!澄清你的问题。
  • “特定词”这个词含糊不清。标记以关闭此问题
  • 如何知道提取哪个词?如果我们已经知道要提取哪个单词,是否只需要确定它在字符串中的位置。

标签: java


【解决方案1】:

您可以通过正则表达式轻松完成。下面是一个例子:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "this is 009876 birthday of mine";
        Pattern pattern = Pattern.compile("009876");
        Matcher  matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 1
    }
}

如果你想检查文本是否包含源字符串(例如“009876”),你可以简单地通过String的contains方法来完成,如下例所示:

public static String search() {
        // TODO Auto-generated method stub
        String text = "this is 009876 birthday of mine";
        String source = "009876";
        if(text.contains(source))
            return text;
        else
            return text;

    }

如果有任何问题,请告诉我。

【讨论】:

  • 问题不在于如何计算特定子字符串的实例数。它也没有询问如何检查它是否包含子环
  • 我不是在问字符串 009876 的位置是什么 .. 我想从整个文本中只提取 009876 .. 我想消除所有其他 .. sop 我的来源是 009876 我想要用给定的文本对这个源进行数学运算。如果匹配,则返回该文本...
【解决方案2】:

你可以这样做:

  class ExtractDesiredString{
      
    static String extractedString;

    public static void main(String[] args) {
        String hello = "this is 009876 birthday of mine";
        Pattern pattern = Pattern.compile("009876");

        if (hello.contains(pattern.toString())) {
            extractedString = pattern.toString();
        }else{
            Assert.fail("Given string doesn't contain desired text")
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2021-10-12
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多