【发布时间】:2018-08-29 21:55:54
【问题描述】:
我正在使用节点来读取文件的内容。我需要匹配一个特定的导入语句,文件看起来像这样。
我只需要匹配包含“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 的行尾的所有行。我只想将导入匹配到以“foo-bar”结尾的行尾。这可以使用 JavaScript 正则表达式吗?另外,如果有比使用正则表达式更好的方法,我也愿意接受其他选择
import([\s\S]*?)(?=foo-bar').*
【问题讨论】:
-
我没有花哨的链接,但你可以试试这个
import(?:(?!import).)*'foo-bar' -
开始更精确地描述模式中的内容。示例:regex101.com/r/mqyudC/1
标签: javascript node.js regex