如何忽略正则表达式主题字符串中的空格? [英] How to ignore whitespace in a regular expression subject string?

查看:41
本文介绍了如何忽略正则表达式主题字符串中的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用正则表达式模式搜索匹配项时,是否有一种简单的方法可以忽略目标字符串中的空格?例如,如果我的搜索是cats",我希望c ats"或cats"匹配.我不能事先去掉空格,因为我需要找到匹配的开始和结束索引(包括任何空格)以突出显示该匹配,并且任何空格都需要存在以进行格式化.

Is there a simple way to ignore the white space in a target string when searching for matches using a regular expression pattern? For example, if my search is for "cats", I would want "c ats" or "ca ts" to match. 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.

推荐答案

您可以在正则表达式中的每个其他字符之间添加可选的空白字符 \s*.虽然可以,但会有点冗长.

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

这篇关于如何忽略正则表达式主题字符串中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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