简体   繁体   English

regexp:仅匹配指定符号内的单独数字

[英]regexp: match only separate numbers inside specified symbols

I am using regular expression in java and can not figure out how to match only numbers inside predefined symbols. 我在Java中使用正则表达式,无法弄清楚如何仅在预定义符号内匹配数字。

here is example of one of my string: 这是我的字符串之一的示例:

some text [1] some and numbers 12, 14 and more text [11,1] another text [3,6, 7] and some more text [5;16]

Is it really possible to retrieve only numbers in square brackets? 真的有可能只检索方括号中的数字吗? in this case: 1 11 1 3 6 7 5 16 This should not match any other symbols in square brackets. 在这种情况下:1 11 1 3 6 7 5 16这应该与方括号中的任何其他符号都不匹配。

I have already tried several options, including: 我已经尝试了几种选择,包括:

Pattern k = Pattern.compile("\\[(\\d+)\\]");

But this only gives works for one number and not others. 但是,这仅给出一个数字的作品,而不给出其他作品。 I have tried to group them, like (?:\\\\[) some code inside (?:\\\\]) without any success. 我试图对它们进行分组,例如(?:\\\\[) some code inside (?:\\\\])但没有成功。

Update 更新

Workaround with grouping: Pattern k = Pattern.compile("\\\\[(\\\\d+)(?:.)?(\\\\d+)?\\\\]"); 分组的解决方法: Pattern k = Pattern.compile("\\\\[(\\\\d+)(?:.)?(\\\\d+)?\\\\]"); But produces the brackets and commas as output. 但是产生括号和逗号作为输出。

You can select those numbers, you can use the following regex: 您可以选择这些数字,可以使用以下正则表达式:

(?:\G|\[)[,;\s]*(\d+)

It only selects the numbers. 它仅选择数字。

See the demo 观看演示

Explanation 说明

  • (?:\\G|\\[) matches the end position of the previous match or an opening bracket (?:\\G|\\[)匹配上一场比赛的结束位置左括号
  • [,;\\s]* matches a comma, a semicolon or a space zero or multiple times [,;\\s]*匹配一个逗号,一个分号或一个零或多次的空格
  • (\\d+) captures the numbers (\\d+)捕获数字

You'll have the numbers in the group 1. 您将在第1组中找到数字。

Just to provide a different workaround that might come in handy when it gets even more complicated: 只是提供一种不同的解决方法,当它变得更加复杂时可能会派上用场:

A much simplier way to achieve your goal is to separate the matching into two stages. 实现目标的一种更简单的方法是将匹配分为两个阶段。 First, match the bracket's occurences with 首先,将括号的出现与

Pattern areas = Pattern.compile("\\[.*?\\]");

which will result in [1] [11,1] [3,6, 7] [5;16] . 这将导致[1] [11,1] [1] [11,1] [3,6, 7] [5;16]

Then for any of these use something like 然后对于任何这些使用类似

Pattern numbers = Pattern.compile("\d+");

to match the actual numbers. 匹配实际数字。

May be this one will help you. 可能这将对您有所帮助。

Try it: 试试吧:

 Pattern k = Pattern.compile("\\[(\\d+)(;?)(\\d+)\\]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM