简体   繁体   English

从URL中提取字符串的一部分 - Java Regex

[英]Extract part of a string from a URL - Java Regex

I'm trying to extract a string between '/' and '.' 我正在尝试在'/'和'。'之间提取一个字符串。 of a URL. 一个URL。 For example, I have a URL like "some.com/part1/part2/part3/stringINeed.xyz". 例如,我有一个像“some.com/part1/part2/part3/stringINeed.xyz”这样的网址。 I need to extract "stringINeed" from the above URL, the one between last '/' and the '.' 我需要从上面的URL中提取“stringINeed”,即最后一个'/'和'。'之间的URL。 nothing else. 没有其他的。

So far, I tried the following and it gives an empty output: 到目前为止,我尝试了以下内容,它给出了一个空输出:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Extract
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "part1/part2/part3/stringINeed.xyz" ;
        Pattern pattern = Pattern.compile("/(.*?).");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
     System.out.println(matcher.group(1));
        }
    }
}

What is wrong with my code. 我的代码有什么问题。 Can anyone help? 有人可以帮忙吗?

Use this regex: 使用这个正则表达式:

[^/.]+(?=\.[^.]+$)

See demo . 演示

In Java: 在Java中:

Pattern regex = Pattern.compile("[^/.]+(?=\\.[^.]+$)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group();
} 

Explanation 说明

  • [^/.]+ matches any chars that are not a slash or a dot [^/.]+匹配任何不是斜杠或点的字符
  • The lookahead (?=\\.[^.]+) asserts that what follows is a dot followed by non-dots and the end of the string 前瞻(?=\\.[^.]+)断言接下来是一个点后跟非点和字符串的结尾

没有正则表达式

str.substring(str.lastIndexOf("/"), str.lastIndexOf(".")).replaceAll("/", "");

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

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