Skip to main content
 首页 » 编程设计

python RE : check if word is only before or after another word

2025年05月04日9jpfss

我正在尝试将变量映射到 Excel 中的特定列。假设我想捕获:

2.4 string 
string 2.4 

但不是:

2.4 string 2.4 
string 

我使用了这个表达式,但是那个表达式匹配了我不想要的 "2.4 string 2.4":

 r"([2]\.[4])?\s*(\"|'|inch)?\s*String\s*([2]\.[4])?\s*(\"|'|inch)?" 

当用于字符串 "2.4 string" 时,group() 函数仅返回 "string" 而不是 "2.4 字符串”

有人可能知道解决方案吗?

请您参考如下方法:

你可以使用这个正则表达式:

^(?:2\.4 string|string 2\.4)$ 

示例 VBScript:

Dim myRegExp 
Set myRegExp = New RegExp 
myRegExp.Pattern = "^(?:2\.4 string|string 2\.4)$" 
If myRegExp.Test(SubjectString) Then 
    ' Successful match 
Else 
    ' Match attempt failed 
End If 

解释

  • ^ anchor 断言我们在字符串的开头
  • `(?: ... ) 是匹配...的非捕获组
  • 2.4 字符串
  • 或|
  • 字符串 2.4
  • $ anchor 断言我们在字符串的末尾