基本思想是我想以“text1.text2”的形式提取字符串的任何部分。我想做的输入和输出的一些示例是:
"employee.first_name" ==> "employee.first_name"
"2 * employee.salary AS double_salary" ==> "employee.salary"
到目前为止,我只有 .split(""),然后找到了我需要的内容和 .split(".")。有没有更干净的方法?
最佳答案
我会使用实际的模式
和迭代查找,而不是拆分字符串
。
例如:
String test = "employee.first_name 2 * ... employee.salary AS double_salary blabla e.s blablabla";
// searching for a number of word characters or puctuation, followed by dot,
// followed by a number of word characters or punctuation
// note also we're avoiding the "..." pitfall
Pattern p = Pattern.compile("[\\w\\p{Punct}&&[^\\.]]+\\.[\\w\\p{Punct}&&[^\\.]]+");
Matcher m = p.matcher(test);
while (m.find()) {
System.out.println(m.group());
}
输出:
employee.first_name
employee.salary
e.s
注意:为了简化模式
,您只能列出类别中形成“.”分隔单词的允许标点符号
例如:
Pattern p = Pattern.compile("[\\w_]+\\.[\\w_]+");
这样,foo.bar*2
将匹配为 foo.bar
关于java - Java中从字符串中提取包含符号的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19075134/