[英]Is there any efficient Java solution/Algorithm to find values in a text field based on key string with delimiter?
Is there any efficient Java solution/Algorithm to find values in a text field based on key string with delimiter? 是否有任何有效的Java解决方案/算法可以根据带分隔符的键字符串在文本字段中查找值?
Example: 例:
Rules: 规则:
I. Key: username Start-Delimiter: ; I.密钥:用户名Start-Delimiter :; End-Delimiter: ; 结束分隔符:;
Need to find a value which if followed by key( in this case username ) and value is between start and end delimiters(in this case ;). 需要找到一个值,如果后跟key(在本例中为username),则值在start和end分隔符之间(在本例中为;)。
II. II。 Key: on Start-Delimiter: ; 关键:on Start-Delimiter :; End-Delimiter: ; 结束分隔符:;
Sample Input: 样本输入:
A user with username ;suren; 具有用户名的用户;确定; logged into the system on ;Thu May 2, 2013 2:30pm; 登录系统; 2013年5月2日星期二下午2:30;
Results: I. username - suren II. 结果:I。用户名 - 确定II。 on - Thu May 2, 2013 2:30pm on - 2013年5月2日星期二下午2:30
Here is an example of what I have tried so far: 这是我到目前为止所尝试的一个例子:
String key = "username ";
String startDelimiter = ";";
String endDelimiter = ";";
String computedPattern = "(\\w+)" + key + startDelimiter + "(\\w+)" + endDelimiter;
Pattern p = Pattern.compile(computedPattern);
Matcher m = p.matcher(
"A user with username ;suren; logged into the system on ;Thu May 2, 2013 2:30pm;");
while( m.find() ) {
System.out.println( "Key:" + m.group(1) + "Value:" + m.group(2) );
}
The problem in your approach arises from your construction of the regex. 您的方法中的问题源于您构造正则表达式。 If you look at Java Docs for the Pattern Class , you see that \\w
matches just word characters: [a-zA-Z_0-9]
如果您查看模式类的 Java Docs,您会看到\\w
仅匹配单词字符: [a-zA-Z_0-9]
It sounds like you just want to match any characters between semicolons after a defined key with any number on spaces in between. 听起来你只想在定义的键之后用分号之间的任何字符匹配,其间的空格上有任何数字。 The right pattern for this is the following: 正确的模式如下:
ArrayList<String> keys = new ArrayList<String>();
keys.add("username");
keys.add("on");
String startDelimiter = ";";
String endDelimiter = ";";
String searchStr = "A user with username ;suren; logged into the system on ;Thu May 2, 2013 2:30pm;";
for (String key : keys) {
Pattern p = Pattern.compile("("+key+")[ ]+?"+startDelimiter+"([^;]+)"+endDelimiter);
Matcher m = p.matcher(searchStr);
while( m.find() ) {
System.out.println("Key: "+m.group(1)+" Value: "+m.group(2));
}
}
The character class [^;]+
does the job for you, since it matches any non empty character sequence with characters different from ";"
字符类[^;]+
为您完成工作,因为它匹配任何非空字符序列,其字符与";"
不同 . 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.