简体   繁体   English

正则表达式匹配内部字符串的开始

[英]Regex match start of string inside lookahead

I am trying to match just the word Hello on the first and third lines: 我正在尝试仅在第一行和第三行中匹配单词Hello:

     Hello should be matched
I do not want this Hello to be matched
Hello should be matched

When I use ^\\s*Hello , things almost work but I do not want the spaces to actually be included in the result. 当我使用^\\s*Hello ,几乎可以正常工作,但是我不希望空格实际包含在结果中。

(?=\\s*)Hello is closer but matches all 3 Hellos. (?=\\s*)Hello ,但与所有3个(?=\\s*)Hello匹配。

I would expected either ^(?=\\s*)Hello or (?=^\\s*)Hello to work, and am confused as to why they don't. 我希望^(?=\\s*)Hello(?=^\\s*)Hello都能正常工作,并且对为什么不起作用感到困惑。 Why don't these work and how can I create a regex that matches only the "Hello" after some whitespace? 为什么这些方法不起作用,如何在空白后创建与“ Hello”匹配的正则表达式?

There is no way to specify where the match came from (first line, third line, etc.). 无法指定匹配的来源(第一行,第三行等)。 The only way to do this properly is to input the sentences, line by line, and programatically keep track of which line the match came from. 正确执行此操作的唯一方法是逐行输入句子,并以编程方式跟踪匹配项来自哪一行。

This regex will match what you are looking for 此正则表达式将匹配您的寻找

\b([H|h]ello)\b

What you need to do is wrap what you are looking for in ( ) which act as the capture goup 您需要做的是将要查找的内容包装在()中,用作捕获对象

Edited - 编辑-

^\s*(Hello)

Create a capture group: 创建一个捕获组:

 str1 = ' Hello should be matched'; str2 = 'I do not want this Hello to be matched'; str3 = 'Hello should be matched'; str1 = str1.match(/^\\s*(Hello)/); if (str1) { str1 = str1[1]; } else { str1 = ''; } str2 = str2.match(/^\\s*(Hello)/); if (str2) { str2 = str2[1]; } else { str2 = ''; } str3 = str3.match(/^\\s*(Hello)/); if (str3) { str3 = str3[1]; } else { str3 = ''; } $('#output').append('str1: ' + str1 + '<br>str2: ' + str2 + '<br>str3: ' + str3 + ''); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="output"></div> 

Here's the solution for you: 这是为您提供的解决方案:

^\b(Hello)\b.*\n.*\n\b(Hello)\b.*$

https://regex101.com/r/vZ9pF8/1 https://regex101.com/r/vZ9pF8/1

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

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