2 个可能的字符串:
1("some text then https://myhost.ab.us2.myDomain.com and then some more text"
或:
2("some text then myhost.ab.us2.myDomain.com and then some more text"
"myDomain.com"
是恒定的,因此我们可以在正则表达式中查找硬编码。
在这两种情况下,它们都不在行的起点,而是在中间。
需要从行中提取"myhost"
(如果匹配(。
我已经尝试过使用"https://"
OR"\s{1}"
的积极外观。https://
本身有效:
Matcher m = Pattern.compile("https://(.+?)\.(.+?)\.(.+?)\.myDomain\.com\s").matcher(input);
我想在那里添加一个"or",以便它与"https://"
或"<space>"
("https://|//s{1}"
(匹配,但它总是抓住整个字符串直到第一个空格的开头。
现在,我已经决定将字符串拆分为String[]
并检查它是否包含"myDomain"
。我为此工作了很长时间,我想了解最佳答案是什么。
我只是采用了一种非正则表达式方法:
public static String extractHost(String logEntry, String domain)
{
logEntry = logEntry.toLowerCase(); -> not needed, just a hint to remember case sensitive stuff ;)
if(logEntry.indexOf("https://") != -1)
{
// contains protocol, must be variant one
return logEntry.substring(logEntry.indexOf("https://")+8,logEntry.indexOf("."));
}
// has to be variant two
int domainIndex = logEntry.indexOf(domain);
if(domainIndex == -1) return null;
int previousDotIndex = -1;
for(int i = domainIndex; i>= 0; i--)
{
if(logEntry.charAt(i) == '.') previousDotIndex = i;
if(logEntry.charAt(i) == ' ') return logEntry.substring(++i,previousDotIndex);
}
return null;
}
变体 #2 实际上是更困难的变体,在这种方法中,您只需从域的索引迭代回找到的第一个空格并存储最近找到的点的位置。那么它只是一个简单的子字符串。
我会使用类似的东西
b(?:https?://)?(w+).(?:w+.)*myDomain.com
这匹配一个可选的https://
前缀,后跟被捕获的主机,后跟一些其他子域(您可以指定有多少{2}
或硬编码它们,如果您知道它总是ab.us2
(,然后myDomain.com
。
在 Java 10 中:
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
var text = "some text then https://myhost.ab.us2.myDomain.com " +
"and then some more text some text then " +
"myhost.ab.us2.myDomain.com and then some more text";
var pat = "\b(?:https?://)?(\w+)\.(?:\w+\.)*myDomain\.com";
var matches = Pattern.compile(pat)
.matcher(text)
.results()
.map((m) -> m.group(1))
.toArray(String[]::new);
System.out.println(Arrays.toString(matches)); // => [myhost, myhost]
}
}
在 Java 8 中:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "some text then https://myhost.ab.us2.myDomain.com " +
"and then some more text some text then " +
"myhost.ab.us2.myDomain.com and then some more text";
String pat = "\b(?:https?://)?(\w+)\.(?:\w+\.)*myDomain\.com";
Matcher matcher = Pattern.compile(pat).matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1)); // => myhost myhost
}
}
}