首页 > 解决方案 > 选择正斜杠之前但任何空格之后的第一个字符

问题描述

我有以下字符串模式,我需要按照描述进行匹配。

在以下每个示例中,我只需要第一个字符/数字。在“/”之前和任何空格之后:

12/5 <--match on 1
x23/4.5 match on x
234.5/7 match on 2
2 - 012.3/4 match on 0

像下面这样的正则表达式显然是不够的:

\d(?=\d\/))

为了清楚 起见,我实际上正在使用带有 js split 的正则表达式,因此它是一些 mpping 函数,它获取每个字符串并在匹配时将其拆分。因此,例如 2 - 012.3/4将被拆分为[ 2 - 0, 12.3/4]等等12/5 to 1, [2/5]

请参阅此处的示例(使用非工作正则表达式):

https://regex101.com/r/N1RbGp/1

标签: javascriptregex

解决方案


试试这样的正则表达式:

(?<=^|\s)[a-zA-Z0-9](?=[^\s]*[/])

分解它:

  • (?<=^|\s)是一个零宽度(非捕获)正向后视,可确保匹配仅在文本开头或空白字符之后立即开始。

  • [a-zA-Z0-9]匹配单个字母或数字。

  • (?=\S*[/])是一个零宽度(非捕获)正向前瞻,它要求匹配的字母或数字后跟零个或多个非空白字符和一个斜线(' /') 字符。

这是代码:

const texts = [
  '12/5',
  'x23/4.5',
  '234.5/7',
  '2 - 012.3/4',
];
texts.push( texts.join(', ') );

for (const text of texts) {
  const rx = /(?<=^|\s)[a-zA-Z0-9](?=\S*[/])/g;

  console.log('');
  console.group(`text: '${text}'`);
  for(let m = rx.exec(text) ; m ; m = rx.exec(text) ) {
    console.log(`matched '${m[0]}' at offset ${m.index} in text.`);
  }
  console.groupEnd();

}

这是输出:

text: '12/5'
  matched '1' at offset 0 in text.

text: 'x23/4.5'
  matched 'x' at offset 0 in text.

text: '234.5/7'
  matched '2' at offset 0 in text.

text: '2 - 012.3/4'
  matched '0' at offset 4 in text.

text: '12/5, x23/4.5, 234.5/7, 2 - 012.3/4'
  matched '1' at offset 0 in text.
  matched 'x' at offset 6 in text.
  matched '2' at offset 15 in text.
  matched '0' at offset 28 in text.

推荐阅读