java - Java中从字符串中提取包含符号的单词

标签 java regex

基本思想是我想以“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/

相关文章:

python - 在之前的任何地方查找具有字母数字字符的非字母数字字符

java - 在 Java 中对字符串中的单词、数字和引用进行正则表达式处理

java - Android Studio 链接引用失败

Java 在字符串数组列表中搜索另一个数组列表中的单词

java - 正则表达式查找所有带有 http url 的 img 标签

Java 正则表达式 - "()"括号

regex - 单词负前瞻的意外结果(R 正则表达式)

regex - 在注释前使用 sed 替换同一行中的多个实例

java - ZonedDateTime 解析异常

java - 我可以将字符串数组 (String[][]) 传递给 Java 中的函数吗?