从字符串中提取子字符串

我的字符串( 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之前和之后的内容是任意的

-product ID string总是以#开头,后跟一个不带空格或其他字符的数字

试试这个

 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,前提是它们由既不是空格也不是数字的字符分隔。

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

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

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

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