Skip to main content
 首页 » 编程设计

python之如何检查一个字符串是否在2个字符串之间,并用正则表达式返回以下字符

2025年05月04日21mayingbao

我想检查一个字符串是否在文本文件中,在其他两个字符串之间,如果为真,则返回与正则表达式匹配的下一个字符串...

我不知道如何实现它!

既然你可能对我的解释感到迷惑,我会用我的问题更好地解释它:

我正在创建一个应用程序(在 python 中)读取 pdf 并将其转换为 .txt。

在此 txt 中,我想找到 pH 并将其返回。我知道我会在第 10 节和第 11 节之间找到它,如下所示:

10. blablablablabla pH 7,6 blablablabla 11. 

所以

  1. 如何在 “10.” 和 “11.” 之间减少我的研究?
  2. 对于 pH 部分,我认为这类似于:

    如果打开(文件).read() 中的“pH”:

  3. 如果我们找到“ph”,我如何编写代码让下一个字符串遵循此正则表达式:re.search("[0-9]{1}[,.]?[ 0-9]?”,文件)

请您参考如下方法:

我会使用以下内容:

regex = re.compile(r"\b10\.(?:(?!\b11\.|\bpH\b).)*\bpH\b\s*(\d+(?:[.,]\d+)?)(?=.*\b11\.)", re.DOTALL) 
pH = regex.search(my_string).group(1) 

测试一下 live on regex101.com .

它的作用是仅当在 10. 和 11. 之间找到时才匹配 pH 值,如果有多个,它会找到第一个。

解释:

\b10\.        # Match 10. (but not 110.) 
(?:           # Start of a (repeating) group that matches... 
 (?!          #   (if we're not at the start of either... 
  \b11\.      #    the number 11. 
 |            #    or   
  \bpH\b      #    the string pH 
 )            #   ) 
 .            # any character (including newlines, therefore the DOTALL option). 
)*            # Repeat as necessary. 
\bpH\b        # Match the string pH 
\s*           # Match optional whitespace 
(             # Match and capture in group 1: 
 \d+          # At least one digit 
 (?:[.,]\d+)? # optionally followed by a decimal part 
)             # End of capturing group  
(?=           # Assert that the following can be matched afterwards: 
 .*           # any number of characters 
 \b11\.       # followed by 11. 
)             # End of lookahead assertion.