正则表达式:单词边界但对于空格,仅行首或行尾 [英] Regex: word boundary but for white space, beginning of line or end of line only

查看:33
本文介绍了正则表达式:单词边界但对于空格,仅行首或行尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些词边界来涵盖这 3 种情况:

I am looking for some word boundary to cover those 3 cases:

  1. 字符串开头
  2. 字符串结束
  3. 留白

是否有类似的东西,因为 \b 还包括 -,/等?

Is there something like that since \b covers also -,/ etc.?

想用上述内容替换此模式中的 \b :

Would like to replace \b in this pattern by something described above:

(\b\d*\sx\s|\b\d*x|\b)

推荐答案

好的,那么你真正的问题是:

OK, so your real question is:

如何匹配一个单位,可选地前面有一个数量,但前提是匹配之前没有任何内容或空格?

How do I match a unit, optionally preceded by a quantity, but only if there is either nothing or a space right before the match?

使用

 (?<!\S)\b(?:\d+\s*x\s*)?\d+(?:\.\d+)?\s*ml\b

说明

(?<!\S):断言在匹配之前不可能匹配到非空格字符.

(?<!\S): Assert that it's impossible to match a non-space character before the match.

\b:匹配一个词边界

(?:\d+\s*x\s*)?:可选匹配量词(仅限整数)

(?:\d+\s*x\s*)?: Optionally match a quantifier (integers only)

\d+(?:\.\d+)?:匹配一个数字(小数可选)

\d+(?:\.\d+)?: Match a number (decimals optional)

\s*ml\b:匹配ml,前面可选空格.

\s*ml\b: Match ml, optionally preceded by whitespace.

这篇关于正则表达式:单词边界但对于空格,仅行首或行尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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