简体   繁体   English

正则表达式在段落中找到第一个出现的事件

[英]Regex Finding the First Occurrence in a Paragraph

I have a pattern like " Hello, I am X and My Father's Name is Y. My Hobby's are Playing etc.". 我有一个模式,如“ 你好,我是X,我的父亲的名字是Y.我的爱好正在玩等等”。

My Target is like to Match the Pattern " Hello, I am X and My ". 我的目标是匹配模式“ 你好,我是X和我的 ”。

I Tried using Regex, but it is always selecting the Second "My". 我尝试使用正则表达式,但它始终选择第二个“我的”。

ie "Hello, I am X and My Father's Name is Y. My " 即“你好,我是X,我父亲的名字是Y.我的

My Regex is (Hello)(.*)(My?) 我的正则表达式是(Hello)(.*)(My?)

I also tried (Hello)(.*)(My?{0}) .But still its not Working. 我也尝试过(Hello)(.*)(My?{0}) 。但仍然没有工作。

Can you help me in this? 你能帮帮我吗?

You need to make the * quantifier lazy : 你需要使*量词懒惰

(Hello)(.*?)(My)

.*? will match as few characters as possible (as opposed to .* which matches as much as it can). 将匹配尽可能少的字符(而不是.*匹配尽可能多的字符)。

使用非贪婪的方法尝试这个正则表达式。

(Hello.*?My)

try this 尝试这个

Hello(.*?)(?=My)(\w{2})

you have a greedy dinosaur but ? 你有贪吃的恐龙但是? will make it a lazy dinosaur 会让它变成懒惰的恐龙

this is a bad dino who eats everything coming in its way .* and .+ is like that only it will eat everything its greedy 这是一个糟糕的恐龙,它会吃掉所有阻碍它的东西。*和。+就是这样,它只会吃掉它贪婪的一切

The bad greedy dino will eat everything and then try to match It will try searching for My but he wont be able to find it because he has already eaten them. 糟糕的贪婪恐龙会吃掉所有东西,然后尝试匹配它会尝试寻找My但他找不到它,因为他已经吃掉了它们。 So, slowly he will start vomiting the letters ....slowly .. one by one unless he finds the y and then the M . 所以,他慢慢地开始呕吐这些字母......慢慢地......除非他找到y然后是M so it matches the last My in your string. 所以它匹配你的字符串中的最后一个。

When we make it lazy, He wont eat the full string and will be content on finding the first My . 当我们把它变得懒惰时,他不会吃完整个字符串,并且会满足于找到第一个My he will eat it and go to sleep :) 他会吃它然后去睡觉:)

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

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