java 正则表达式匹配一个数字后跟空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17020720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:44:28  来源:igfitidea点击:

regex to match a number followed by spaces

javaregex

提问by artfullyContrived

I'm looking to use reg-ex to split the following string

我正在寻找使用 reg-ex 来拆分以下字符串

1 hi my name is John. 2 I live at house 32. 3 I see stars.

to

[hi my name is John,  I live at house 32. , I see stars]

Note that am trying to split on digit followed by a space

请注意,我试图在数字后跟一个空格上拆分

回答by h2ooooooo

Split on /(^|\b\s+)\d+\s+/g.

拆分/(^|\b\s+)\d+\s+/g

Explanation:

解释:

  • (^|\b\s+)A collection of either ^or \b\s+)
    • ^Start of the stringOR
    • \b\s+a word boundaryfollowed by a space/tab repeated 1 or more times
  • \d+A digit between 0 and 9 repeated 1 or more times(so it'd match 1, 12, 123, etc.)
  • \s+A space/tab repeated 1 or more times
  • (^|\b\s+)^\b\s+) 的集合
    • ^字符串的开头OR
    • \b\s+一个字边界后跟一个空格/片重复1次或多次
  • \d+0 到 9 之间的数字重复 1 次或多次(因此它匹配 1、12、123 等)
  • \s+空格/制表符重复 1 次或多次

Edit:

编辑

(^|\.\s+)\d+\s+might work better for you.

(^|\.\s+)\d+\s+可能更适合你。

回答by Babar

Maybe this will do: [0-9]{1}[\ ]

也许这会做: [0-9]{1}[\ ]

回答by gitaarik

Split on:

拆分:

/\d+ /

Only the first match will be empty because it's the match just before the first number: 1, so you gotta ignore that one.

只有第一个匹配项是空的,因为它是第一个数字之前的匹配项: 1,所以你必须忽略那个。