如何忽略正则表达式主题字符串中的空格,但前提是它位于换行符之后?
使用正则表达式模式搜索匹配项时,忽略目标字符串中的空格的最佳方法是什么,但前提是空格位于换行符 (\n) 之后?例如,如果我的搜索是“cats”,我希望“c\n ats”或“ca\n ts”匹配,但不匹配“c ats”,因为换行符后面没有空格。我无法事先删除空格,因为我需要找到匹配的开始和结束索引(包括任何空格),以便突出显示该匹配,并且出于格式化目的,需要存在任何空格。
What is the best way to ignore the white space in a target string when searching for matches using a regular expression pattern, but only if the whitespace comes after a newline (\n)? For example, if my search is for "cats", I would want "c\n ats" or "ca\n ts" to match but not "c ats" since the whitespace doesn't come after a newline. I can't strip out the whitespace beforehand because I need to find the begin and end index of the match (including any whitespace) in order to highlight that match and any whitespace needs to be there for formatting purposes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的正则表达式引擎支持环视断言,请使用正向环视断言来检查前面是否存在换行符:
If the regex engine you're using supports lookaround assertions, use a positive lookbehind assertion to check for the presence of a preceding newline:
“使用正则表达式模式搜索匹配项时,忽略目标字符串中的空格的最佳方法是什么”
我会动态构造一个正则表达式,插入
(?:\n\s)?
每个字符之间。输出:
"What is the best way to ignore the white space in a target string when searching for matches using a regular expression pattern"
I would construct a regex dynamically, inserting a
(?:\n\s)?
between each character.The output:
我根据您列出的规则制作了一个小红宝石片段。这是您要找的吗?
I have made a small ruby snippet based on the rules you have listed. Is this what you are looking for?