如何在正则表达式中提取数字,然后是多个条件

时间:2015-07-21 11:48:18

标签: java regex string

我有以下字符串:

"these 13 keys are 4, C1, C2, 11, 12, 26, 54, 70, 75, 80, 87, 89 and 95 some other 2 text"

我正在尝试使用Regex提取密钥。 为了使密钥有效,有几个条件:

  • 数字需要 后的单词are
  • 最后一个数字以前缀and
  • 结尾

所以结果应该是:

4 C1 C2 11 12 26 54 70 75 {{ 1}} 80 87 89

数字9513不应作为关键结果返回。

我使用2,但第一个和最后一个结果不正确(获取(?= )[^,]+13 keys are 4)作为结果。

4 个答案:

答案 0 :(得分:2)

您可以使用此表达式提取第一部分:are (([\d, A-Z]+) and \d+)。这将产生以下字符串:4, C1, C2, 11, 12, 26, 54, 70, 75, 80, 87, 89, and 95作为正则表达式组。

其次,你可以简单地执行split(\s*(,|and)\s*)这应该依次为,生成由and分隔的值,如果是最后一个,则由 Bitmap bitmap = ((BitmapDrawable) WallpaperView.getDrawable()).getBitmap(); Intent setAs = new Intent (Intent.ACTION_ATTACH_DATA); setAs.setType("image/jpg"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,bytes); File f = new File (Environment.getExternalStorageDirectory()+ File.separator + "/my_tmp_file.jpg"); try{ f.createNewFile(); FileOutputStream fo = new FileOutputStream(f); fo.write(bytes.toByteArray()); }catch (IOException e){ e.printStackTrace(); } setAs.setDataAndType (Uri.parse(Environment.getExternalStorageDirectory()+ File.separator + "/my_tmp_file.png"),"image/jpg"); setAs.putExtra("mimeType", "image/jpg"); startActivity(Intent.createChooser(setAs, "Set Image As")); 文本生成。 / p>

答案 1 :(得分:1)

这是另一种选择:

(\w+(?=,)|(?<=and\s)\w+)

Regex live here.

解释

(                   # start of matching group
    \w+             # a key
    (?=,)           # followed by a comma - without taking it
  |                 # or
    (?<=and\s)      # preceded by "and " - without taking it
    \w+             # a key
)                   # end of matching group

希望它有所帮助。

答案 2 :(得分:0)

试试这个:

(?<=are\s|and\s|,\s)[A-Z0-9]{1,2}

其中:

  • (?<=are\s|and\s|,\s) - 看后面,正则表达式的其余部分前面是: 带有空格字符的“是”,“和”或“,”;
  • [A-Z0-9]{1,2} - 一个或两个(如示例中)小数或字母(此部分取决于准确允许的键,它也可以替换为例如\w\d - 一个字母或小数,和十进制或用\w{1,2}两个单词字符(A-Za-z0-9 _))

DEMO

Java实现:

public class RegexTest{
    public static void main(String[] args){
        String string = "these 13 keys are 4, C1, C2, 11, 12, 26, 54, 70, 75, 80, 87, 89, and 95 some other 2 text";
        Pattern pattern = Pattern.compile("(?<=are\\s|and\\s|,\\s)[A-Z0-9]{1,2}");
        Matcher matcher = pattern.matcher(string);
        while(matcher.find()) {
            System.out.print(string.substring(matcher.start(), matcher.end())+" ");
        }
    }
}

结果:

  

C1 C2 11 12 26 54 70 75 80 87 89 95

答案 3 :(得分:0)

    String test = "these 13 keys are 4, C1, C2, 11, 12, 26, 54, 70, 75, 80, 87, 89, and 95 some other 2 text";
    String[] t  = test.split("are")[1].split("and")[0].split(",");
String t95 = test.split("are")[1].split("and")[1].split("some")[0];    
for(String st : t){
            System.out.println(st);
    }

只是一个快速的解决方案:)