我正在使用node读取文件的内容。我需要匹配特定的导入语句,其中该文件看起来像这样。
我只需要匹配包含“foo-bar”包的行或多行。我对获取该包中的导入很感兴趣。
它也可以像这样跨越多行。
我尝试使用这个正则表达式,但它匹配了从“import”到包含foo-bar的行的末尾的所有行。我只想匹配从import到以“foo-bar”结尾的行的末尾或行。在JavaScript正则表达式中是否可能实现这一点?此外,如果有比使用正则表达式更好的方法,我也可以考虑其他选项。
单行示例: https://regex101.com/r/U1j2G6/1 多行示例: https://regex101.com/r/kcA7gd/1
我只需要匹配包含“foo-bar”包的行或多行。我对获取该包中的导入很感兴趣。
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { foo, bar, fooBar } from 'foo-bar'
import { anotherThing } from 'another-module'
它也可以像这样跨越多行。
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import {
foo,
bar,
fooBar
} from 'foo-bar'
import { anotherThing } from 'another-module'
我尝试使用这个正则表达式,但它匹配了从“import”到包含foo-bar的行的末尾的所有行。我只想匹配从import到以“foo-bar”结尾的行的末尾或行。在JavaScript正则表达式中是否可能实现这一点?此外,如果有比使用正则表达式更好的方法,我也可以考虑其他选项。
import([\s\S]*?)(?=foo-bar').*
单行示例: https://regex101.com/r/U1j2G6/1 多行示例: https://regex101.com/r/kcA7gd/1
import[^']+(?= from 'foo-bar')
这里 和 这里。 - Paoloimport(?:(?!import).)*'foo-bar'
。 - Adam Hvar res = str.match(/import {\s*([^}]+)} from 'foo-bar'/)[1]
。此外,请参见regex101上的演示。 - bobble bubble