如何用正则表达式匹配表达式后的第一个单词? [英] How to match the first word after an expression with regex?

查看:83
本文介绍了如何用正则表达式匹配表达式后的第一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在本文中:

Lorem ipsum dolor 坐 amet,consectetur adipiscing 精英.Nunc eutellus vel nunc pretium lacinia.Proin sed lorem.Cras sed ipsum.Nunc a libero quis risus sollicitudin imperdiet.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu tellus vel nunc pretium lacinia. Proin sed lorem. Cras sed ipsum. Nunc a libero quis risus sollicitudin imperdiet.

我想匹配 'ipsum' 后面的单词.

I want to match the word after 'ipsum'.

推荐答案

这听起来像是后视的工作,但您应该意识到并非所有正则表达式风格都支持它们.在您的示例中:

This sounds like a job for lookbehinds, though you should be aware that not all regex flavors support them. In your example:

(?<=\bipsum\s)(\w+)

这将匹配ipsum"作为一个完整单词后跟一个空格的任何字母字符序列.它匹配ipsum"本身,您无需担心在以下情况下重新插入它,例如替换.

This will match any sequence of letter characters which follows "ipsum" as a whole word followed by a space. It does not match "ipsum" itself, you don't need to worry about reinserting it in the case of, e.g. replacements.

不过,正如我所说,某些风格(例如 JavaScript)根本不支持后视.许多其他人(事实上,大多数)只支持固定宽度"后视——所以你可以使用这个例子而不是任何重复运算符.(换句话说,(?<=\b\w+\s+)(\w+) 不会工作.)

As I said, though, some flavors (JavaScript, for example) don't support lookbehind at all. Many others (most, in fact) only support "fixed width" lookbehinds — so you could use this example but not any of the repetition operators. (In other words, (?<=\b\w+\s+)(\w+) wouldn't work.)

这篇关于如何用正则表达式匹配表达式后的第一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆