繁体   English   中英

选择正斜杠之前但任何空格之后的第一个字符

[英]Select the first character before a forward slash but after any space

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

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

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]将拆分12/5 to 1, [2/5]等等。

在此处查看示例(使用非工作正则表达式):

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

试试这样的正则表达式:

(?<=^|\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.

如果您希望能够扫描整个文档:

/(?<=(^|\s))\S(?=\S*\/)/g

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

 s = `12/5 x23/4.5 234.5/2 534/5.6 - 49.55/6.5 234.5/7`; console.log(s.match(/(?<=(^|\\s))\\S(?=\\S*\\/)/g));

但是如果你想在一个短字符串中提取那个字符:(你的意思是前面有一个空格吗?)

它会是/\\s(\\S)\\S*\\//

 const arr = [ " 12/5", " x23/4.5", " 234.5/7", " 2 - 012.3/4" ]; arr.forEach(s => { let result = s.match(/\\s(\\S)\\S*\\//); if (result) console.log("For", s, "result: ", result[1]) });

但是如果“行首”没问题......所以前面不需要空格,那么/(^|\\s)(\\S)\\S*\\//

 const arr = [ "12/5", "x23/4.5", "234.5/7", "2 - 012.3/4" ]; arr.forEach(s => { let result = s.match(/(^|\\s)(\\S)\\S*\\//); if (result) console.log("For", s, "result: ", result[2]) });

但实际上,如果你的意思不是字面上的空间而是一般的边界:

 const arr = [ "12/5", "x23/4.5", "234.5/7", "2 - 012.3/4" ]; arr.forEach(s => { let result = s.match(/\\b(\\S)\\S*\\//); if (result) console.log("For", s, "result: ", result[1]) });

此正则表达式中的第一组匹配您要求的字符:

([^\s])[^\s]*/

你也可以只使用:

[^\s]+/

并使用匹配的第一个字符(或者您可能仍然需要其余的字符)。

暂无
暂无

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

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