我有一个不规则的表达式,我从活动目录中读取,例如“描述:John Newman登录:03.26.2018 9:26:29”。单词的数量可以不同。我总是希望收到“登录”或“注销”,这一切都取决于输入数据。
我试过了:
String a = Objects.toString(attrs.get("description"));//received values from active directory
String b = a.split(":")[1];
Ноэтодаетмне
John Newman Logged on
你可以帮帮我吗?提前谢谢。
答案 0 :(得分:3)
当您知道要查找的String时,可以尝试以下操作。
String s="description: John Newman Logged on: 03.26.2018 9:26:29";
String log1 = null;
if(s.toLowercase().contains("logged on")){
log1 = "Logged on"; // Your desired string
}else if(s.toLowercase().contains("logged off")){
log1 = "Logged off"; // Your desired string
}
或简单
String log1 = (s.toLowercase().contains("logged on")) ? "Logged on":(s.toLowercase().contains("logged off")) ? "Logged off" : null;
如果您认为logged on
也可以是用户姓名的一部分(子字符串),请使用边界。
答案 1 :(得分:2)
根据我的理解,您正在尝试从主String中提取Logged on: 03.26.2018 9:26:29
信息。
试试这个:
String s="description: John Newman Logged on: 03.26.2018 9:26:29";
int indx=s.indexOf("Logged on");
//will return the index of the substring which is 26 in this case.
//I hope I didn't count wrong.
String log=s.substring(indx);
//returns Logged on: 03.26.2018 9:26:29
修改:仅提取Logged on
Logged on
(9)的长度是固定的,因此我们可以使用它来提取 它
int endIndx=indx+9; //endIndx becomes 35 and Logged on ends at 34
//in the below method indx is inclusive and endIndx is exclusive
//Reason why endIndx points to colon so that we get everything starting from indx to endIndx-1
String log1=s.substring(indx,endIndx);
//returns Logged on