我有下面的字符串模式,我需要匹配,正如所描述的。
我只需要以下每一个例子的第一个字符/数字。在“/”之前和任何空格之后:
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拆分,所以它是一些混合函数,它接收每个字符串,并在匹配时将其拆分。例如,2 - 012.3/4将被拆分为[ 2 - 0, 12.3/4]和12/5 to 1, [2/5],等等。
参见示例(在这里使用非工作正则表达式):
发布于 2020-01-16 02:07:17
尝试这样的正则表达式:
(?<=^|\s)[a-zA-Z0-9](?=[^\s]*[/])把它拆开:
(?<=^|\s)是一种零宽度(非捕获)正向查找,它确保匹配只在文本开始或空白之后立即开始,character.[a-zA-Z0-9]匹配单个字母,或者digit.(?=\S*[/])是零宽度(非捕获)正向查找,它要求匹配的字母或数字后面跟着零或多个非空格字符和solidus ('/')字符。下面是代码:
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.发布于 2020-01-16 01:16:01
如果您希望能够扫描整个文档:
/(?<=(^|\s))\S(?=\S*\/)/ghttps://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])
});
发布于 2020-01-16 01:21:13
这个正则表达式中的第一个组与您要求的字符匹配:
([^\s])[^\s]*/你也可以用:
[^\s]+/并使用匹配的第一个字符(或者您可能还需要其他字符)。
https://stackoverflow.com/questions/59761738
复制相似问题