用Java正则表达式替换全部以获取主机名。

huangapple go评论83阅读模式
英文:

java regex replace all to get hostname

问题

我有以下的 URL:

https://mydemo.company/pages/pag1

我想从 URL 字符串中获取 mydemo,
我们能否有一个可以在 replaceAll 中使用的正则表达式,以排除其他所有内容并获得 mydemo:

replaceAll('regextoNegate', '')

(请注意,我只提供了翻译后的部分,符合您的要求。如果您需要更多帮助,请随时提问。)

英文:

I have the following url :

https://mydemo.company/pages/pag1

I want get mydemo from url string,
Can we have the regex that can be used in replaceAll to negate everything else and get mydemo

 replaceAll('regextoNegate','')

答案1

得分: 1

.*?\/\/(.*)\..*
**对上述正则表达式的解释:**
- **```.*?\/\/```** - 在`//`之前懒惰地匹配所有内容。
- **```(.*)```** - 表示第一个捕获组,匹配`//`之后和最后一个`.`之前的所有内容,因为它是贪婪匹配。
- **```\.```** - 字面匹配`.`。
- **```.*```** - 匹配`.`之后的所有内容,零次或多次。
- **```$1```** - 表示第一个捕获组。


----------


[![图片表示][1]][1]

你可以在[**这里**](https://regex101.com/r/NNrrTE/1)找到上述正则表达式的示例实现。

**在Java中的示例实现:**
```java
public class Main
{
    public static void main(String[] args) {
        String str = "https://mydemo.company/pages/pag1\nhttps://mydemo.secondString.company/pages/pag1";
        System.out.println(str.replaceAll(".*?\\/\\/(.*)\\..*", "$1"));
    }
}

你可以在这里找到上述实现的示例运行。


<details>
<summary>英文:</summary>

You may try:

    .*?\/\/(.*)\..*
**Explanation of the above regex:**
- **```.*?\/\/```** - Matches everything lazily before `//`.
- **```(.*)```** - Represents first capturing group matching everything after the `//` and before the last `.` since it is a greedy match.
- **```\.```** - Matches `.` literally.
- **```.*```** - Matches everything after `.` zero or more time.
- **```$1```** - Represents the first captured group.


----------


[![Pictorial Representation][1]][1]

You can find the sample implementation of the above regex in [**here.**](https://regex101.com/r/NNrrTE/1)

**Sample implementation in java:**

public class Main
{
public static void main(String[] args) {
String str = "https://mydemo.company/pages/pag1\nhttps://mydemo.secondString.company/pages/pag1";
System.out.println(str.replaceAll(".?\/\/(.)\..*", "$1"));
}
}

You can find the sample run of the above implementation in [**here.**](https://onlinegdb.com/H1NQMHDC8)
  
[1]: https://i.stack.imgur.com/gzZey.png

</details>



# 答案2
**得分**: 1

你可以使用这个基于简单替换的正则表达式:

```java
str = str.replaceAll("^https?://|\\..+$", "");

正则表达式演示

这里有两个替换部分:

  • ^https?://:匹配以 http://https:// 开头
  • |:或者
  • \\..+$:匹配从第一个点开始到结尾的子字符串

替换成一个空字符串。

英文:

You can use this simple alternation based regex:

str = str.replaceAll(&quot;^https?://|\\..+$&quot;, &quot;&quot;);

RegEx Demo

There are 2 alternations:

  • ^https?://: Match starting http:// or https://
  • |: OR
  • \\..+$: Match substring starting from first dot to end

Replacement is just an empty string.

huangapple
  • 本文由 发表于 2020年6月29日 18:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/62635665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定