簡體   English   中英

如何從字符串中獲取子字符串而不拆分?

[英]How to get substring from string without split?

String str = "internet address : http://test.com Click this!";

我想得到“ http://test.com ”,所以我是這樣寫的。

String[] split = str.split(" ");
for ( int i = 0 ; i < split.length ; i++ ) {
    if ( split[i].contains("http://") ) {
        return split[i];
    }
}

但我認為這是無效的。 如何更輕松地獲得它?

假設您始終具有相同的格式(一些文本:URL 更多文本),這可以工作:

public static void main(String[] args) throws IOException {
    String str = "internet address : http://test.com Click this!";
    String first = str.substring(str.indexOf("http://"));
    String second = first.substring(0, first.indexOf(" "));
    System.out.println(second);
}

但更好的是正則表達式,如不同答案中所建議

通常,這是使用正則表達式或使用indexOfsubstring

使用正則表達式,可以這樣做:

    // This is using a VERY simplified regular expression
    String str = "internet address : http://test.com Click this!";
    Pattern pattern = Pattern.compile("[http:|https:]+\\/\\/[\\w.]*");
    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        System.out.println(matcher.group(0));
    }

您可以在此處閱讀簡化的原因: https : //mathiasbynens.be/demo/url-regex - tl;dr:URL 的問題在於它們可以有許多不同的有效模式。

有了 split,就有一種利用 Java 的 URL 類的方法:

   String[] split = str.split(" ");

    for (String value : split) {
        try {
            URL uri = new URL(value);
            System.out.println(value);
        } catch (MalformedURLException e) {
            // no valid url
        }
    }

您可以在此處的 OpenJDK 源代碼中檢查它們的驗證。

我對正則表達式的嘗試

String regex = "http?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)";
String str = "internet address : http://test.com Click this!";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(0));
}

結果:

http://test.com

來源: 這里

在字符串中找到http:// ,然后向前和向后查找空格:

int pos = str.indexOf("http://");
if (pos >= 0) {
  // Look backwards for space.
  int start = Math.max(0, str.lastIndexOf(' ', pos));

  // Look forwards for space.
  int end = str.indexOf(' ', pos + "http://".length());
  if (end < 0) end = str.length();

  return str.substring(start, end);
}

不清楚輸入字符串的結構是否是常量,但是,我會這樣做:

    String str = "internet address : http://test.com Click this!";
    // get the index of the first letter of an url
    int urlStart = str.indexOf("http://");
    System.out.println(urlStart);
    // get the first space after the url
    int urlEnd = str.substring(urlStart).indexOf(" ");
    System.out.println(urlEnd);
    // get the substring of the url
    String urlString = str.substring(urlStart, urlStart + urlEnd);
    System.out.println(urlString);

我只是為此做了一個快速解決方案。 它應該非常適合你。

package Main.Kunal;

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

public class URLOutOfString {

    public static void main(String[] args) {
        String str = "internet address : http://test.com Click this!, internet address : http://tes1t.com Click this!";
        List<String> result= new ArrayList<>();
        int counter = 0;
        final Pattern urlPattern = Pattern.compile(
                "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
                        + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
                        + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

        Matcher matcher = urlPattern.matcher(str);

        while (matcher.find()) {
            result.add(str.substring(matcher.start(1), matcher.end()));
            counter++;
        }

        System.out.println(result);

    }

}

這將找到字符串中的所有 URL 並將其添加到 arraylist。 您可以根據業務需要使用它。

你可以使用正則表達式

String str = "internet address : http://test.com Click this!";
Pattern pattern = Pattern.compile("((http|https)\\S*)");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM