使用一个或多个单词作为搜索关键字匹配行的正则表达式

时间:2017-04-07 08:09:13

标签: java regex string

假设我们有一个字符串格式如下:

  

" part1 part2:part3"

part1 part2 大多数情况下,一个单词(包括小写和大写字母)和 part3 可以是数字的任意组合字符(包括标点符号)。此外,Subject

之前或之后可以有多个空格

我打算写一个正则表达式匹配这样的字符串。例如,如果示例字符串如下:

:

搜索金额总计总金额等密钥我想匹配 sample1 字符串。同时搜索公司等关键字我想匹配 sample2 字符串。

  

编辑:

     

因此,如果我们有一个类似示例的字符串,则通过搜索   " Total"," Amount",或" Total Amount"我们应该退回样本   字符串作为匹配。并且, 重要 :1)不仅行应包含键,而且还应遵循指定的行格式,2)用户输入

这是我现在的正则表达式:

String sample1 = "Total Amount: $1,000";
String sample2 = "Company: Google Inc.";

但是,我的正则表达式与整行不匹配。值得指出的是,我使用 Java 并假设样本字符串存储在样本中我使用String reg = "[tTOoTtAaLl0-9.,\/#!$%\^&\*;:{}=\-_`~( ) ]+:[A-Za-z0-9.,\/#!$%\^&\*;:{}=\-_`~( ) ]+"; 来检查字符串是否匹配。

1 个答案:

答案 0 :(得分:0)

不确定我是否理解您的要求,但是根据您的数据以及我想要获得的内容,您有两个示例:

1)仅获得金额的示例:https://regex101.com/r/7P2Bad/3

2)获取匹配的完整字符串的示例:https://regex101.com/r/7P2Bad/2

考虑到使用Java(与regex101.com的语法不同)正则表达式,你应该转义一些字符。

处理以下案件:

aaa bbb!   : $34 
Total Amount: $1,000
njhjh hjh: $33
Google Google1: $100

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {
    // Case1: Getting full string
    Pattern p1 = Pattern.compile("(.*\\s?.*:\\s?\\$.*)");
    Matcher matcher1 = p1.matcher("Total Amount: $1,000");
    if (matcher1.matches()) {
        System.out.println("Full string matched: " + matcher1.group(1));
    }

    // Case2: Getting only the amount of dollars
    Pattern p2 = Pattern.compile(".*\\s?.*:\\s?\\$?(.*)");
    Matcher matcher2 = p2.matcher("Total Amount: $1,000");
    if (matcher2.matches()) {
        System.out.println("Amount only from matched string: " + matcher2.group(1));
    }
}
}

输出:

Full string matched: Total Amount: $1,000
Amount only from matched string: 1,000

评论后编辑:

然后,在阅读完评论后,您需要这样的内容:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
public static void main(String[] args) {
    String userKey = "Amount";
    System.out.println("Full string matched: " + getMatch(userKey));

    userKey = "total";
    System.out.println("Full string matched: " + getMatch(userKey));
}

private static String getMatch(String key) {
    // Case: Getting full string for userKey (case insensitive) matches
    Pattern p1 = Pattern.compile(String.format("(?i)(.*%s.*\\s?.*:\\s*?\\$.*)", key));
    Matcher matcher1 = p1.matcher("Total Amount: $1,000");
    if (matcher1.matches()) {
        return matcher1.group(1);
    }
    return "";
}
}

输出:

Full string matched: Total Amount: $1,000
Full string matched: Total Amount: $1,000

说明:

  • (?i)>搜索不区分大小写的
  • %s >只需使用String.format方法将userKey var放在该%s占位符