javascript - 选择正斜杠之前但任何空格之后的第一个字符
问题描述
我有以下字符串模式,我需要按照描述进行匹配。
在以下每个示例中,我只需要第一个字符/数字。在“/”之前和任何空格之后:
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]
。
请参阅此处的示例(使用非工作正则表达式):
解决方案
试试这样的正则表达式:
(?<=^|\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.
推荐阅读
- r - R - 如何在循环中使 stringi str_extract 模式参数化
- r - 如果使用的元素从 R 中的向量中选择下一个
- ios - 按键(日期)排序字典
- asp.net - ASP.NET MVC - 同一解决方案中的多个控制器冲突
- sqlite - 嵌入式应用程序中的 SQLite“数据库磁盘映像格式错误”错误
- intellij-idea - 如何使用 IntelliJ Diagrams 查看实际依赖关系?
- python-3.x - Flask & Python:如何使用格式 HH:MM: SS.SSS in Flask 绘制带有月份 x 轴和 y 轴(数据)和时间的图表
- android - 尝试在包含空字段的 ArrayList 变量上使用 parcelable 时出现 kotlin.TypeCastException
- c++ - std::atomic 加载和存储都需要吗?
- android - Android:无法使用 Android Studio 3.6 构建项目