从字符串中提取子字符串

时间:2013-06-06 12:47:51

标签: java regex

我的字符串(MY_STRING)的内容可以采用以下格式:

bla bla...this is the id of product bla bla:#31 5 2 0000 12please verify bla bla ...

bla bla...this is the id of product bla bla: #31 5 2 0000 12, please verify bla bla...

bla bla...this is the id of product bla bla: #31 5 2 0000 12 please verify bla bla...

我想从字符串中提取产品ID。上例中的产品ID为#31 5 2 0000 12

产品ID的格式是以#开头,后跟随机数(长度无限制),数字之间的空格也是任意的

我目前提取产品ID的代码是:

Pattern pattern = Pattern.compile("^#\\d+(\\s+\\d+)*$");
Matcher matcher = pattern.matcher(MY_STRING);
if(phoneNrMatcher.find()){
    System.out.println(matcher.group(0));                   
}

但它不起作用,有人可以帮助我哪里出错了吗?可能是正则表达式?

注意:

- 在我的例子中,之前和之前的内容ID #31 5 2 0000 12 任意

- 产品ID字符串始终以#开头,后跟一个不带空格或其他字符的数字

2 个答案:

答案 0 :(得分:3)

试试这个

String test = "bla bla...this is the tag id of product: #31 5 2 0000 12, please verify bla bla...";
// explanation of the Pattern:
//                                |starts with "#"
//                                | |directly followed by digits only
//                                | |   |character class including digits or spaces
//                                | |   |       |ad lib (greedy quantifier)
Pattern pattern = Pattern.compile("#\\d+[\\d\\s]+");

Matcher matcher = pattern.matcher(test);
// using a while group here so you may have multiple matches
while (matcher.find()) {
    System.out.println(matcher.group());
}

输出

#31 5 2 0000 12

解释

在这种情况下,您无需在模式中提及行的开头或结尾。 此外,我的示例中的Pattern允许您在同一个String中找到多个id,前提是它们由既不是空格也不是数字的字符分隔。

答案 1 :(得分:1)

您有正则表达式(^$)的输入锚点的开头和结尾。删除它们!

输入锚的开头使得正则表达式无法在输入开头之外的任何地方匹配,顾名思义;输入锚点的结尾是这样的...你得到了图片。除此之外,正则表达式还不错。

(顺便说一句,你可以使用.group(),它与.group(0)相同)

(顺便说一下2:如果你在一个输入中有多个数字,则循环遍历m.find()

相关问题