如何获取两个字符串之间的文本? [英] How To get text between 2 strings?

查看:39
本文介绍了如何获取两个字符串之间的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面给出了我想从中提取文本的字符串.

String is given below from which i want to extract the text.

字符串:

Hello Mr John and Hello Ms Rita

正则表达式

Hello(.*?)Rita

我试图在Hello"和Rita"这两个字符串之间获取文本我正在使用上面给出的正则表达式,但它给了我

I am try to get text between 2 strings which "Hello" and "Rita" I am using the above given regex, but its is giving me

Mr John and Hello Ms

这是错误的.我只需要女士" 谁能帮我为这种情况编写适当的正则表达式?

which is wrong. I need only "Ms" Can anyone help me out to write proper regex for this situation?

推荐答案

使用 tempered greedy令牌:

Hello((?:(?!Hello|Rita).)*)Rita
       ^^^^^^^^^^^^^^^^^^^

在此处查看正则表达式演示

(?:(?!Hello|Rita).)* 是缓和的贪婪标记,它只匹配不是 HelloRita<的文本/代码>.如果您需要检查整个单词,您可以添加单词边界 \b.

The (?:(?!Hello|Rita).)* is the tempered greedy token that only matches text that is not Hello or Rita. You may add word boundaries \b if you need to check for whole words.

为了得到一个两端没有空格的 Ms,使用这个 regex变化:

In order to get a Ms without spaces on both ends, use this regex variation:

Hello\s*((?:(?!Hello|Rita).)*?)\s*Rita

? 添加到 * 将形成一个惰性量词 *? 匹配尽可能少的字符以找到匹配项,并且 \s* 将匹配零个或多个空格.

Adding the ? to * will form a lazy quantifier *? that matches as few characters as needed to find a match, and \s* will match zero or more whitespaces.

这篇关于如何获取两个字符串之间的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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