首页 > 解决方案 > 如何从字符串中仅提取有效方程

问题描述

提取以下文本中的所有有效方程。

我尝试了一些正则表达式,但似乎都没有。希望在 R 中使用suborgsub功能。

myText <- 'equation1: 2+3=5, equation2 is: 2*3=6, do not extract 2w3=6'
expected result : 2+3=5  2*3=6

标签: rregex

解决方案


这是一个基本的 R 方法。我们可以使用grepexpr()在输入字符串中查找多个方程匹配:

x <- c("equation1: 2+3=5, equation2 is: 2*3=6, do not extract 2w3=6")
m <- gregexpr("\\b\\w+(?:[+-\\*]\\w+)+=\\w+\\b", x)
regmatches(x, m)

[[1]]
[1] "2+3=5" "2*3=6"

这是正则表达式的解释:

\\b\\w+           match an initial symbol
(?:[+-\\*]\\w+)   then match at least one arithmetic symbol (+-\*) followed
                  by another variable

+=\\w+            match an equals sign, followed by a variable

推荐阅读