咕噜声 以100%的安全方式分析正则表达式的代码
在更高层次上,Grubber也暴露出帮助器功能来解析一个文件在许多语言中的依赖性(Javascript, Typescript, Cs, Scs, Python, Rust, C / C++, Nim,.
怎么会?
用正则表达式解析源文件的问题在于,您无法确定您的匹配没有被评论或没有在字符串内被评论.
比如说你在寻找所有人 const 在 Javascript 文件中的语句 - 您将使用类似 :
/\bconst\s+/g;
但是,如果你想要分析的文件 是类似的东西:
const x = 12;
// const y = 13;
let z = "const ";
那你就跟三个比 const 当只有一个应该匹配.
Grubber理解什么是字符串,什么是评论和代码,这样你就可以非常轻松地克服这个问题:
import { grub } from "@digitak/grubber";
const content = `
const x = 12
// const y = 13
let z = "const "
`;
const results = grub(content).find(/\bconst\s+/);
console.log(results.length); // will print 1 as expected
为了示威,我们使用了简单的regex,但记住Ecmascript是一个棘手的语言! 有效寻找所有
const声明需要更精细的规范。 实例:foo.const = 12将匹配。 语言在每个语句结尾处使用分号或严格缩进,以100%安全的方式解析要容易得多.
安装
使用您最喜欢的软件包管理器 :
npm install @digitak/grubber
格鲁贝尔 API
Grubber 输出一个主要函数 grub数字 :
export function grub(
source: string,
languageOrRules: LanguageName | Rule[] = "es",
): {
// find one or more expressions and return an array of fragments
find: (...expressions: Array<string | RegExp>) => Fragment[];
// replace one or more expressions and return the patched string
replace: (
...fromTos: Array<{
from: string | RegExp;
to: string | RegExp;
}>
) => string;
// find all dependencies (ex: `imports` in Typescript, `use` in Rust)
findDependencies: () => Fragment[];
// replace all dependencies by the given value
// you can use special replace patterns like "$1" to replace
// with the first captured group
replaceDependencies: (to: string) => string;
};
这个 find 财务报告和审定财务报表 findDependencies 两种方法都返回一系列碎片:
export type Fragment = {
slice: string; // the matched substring
start: number; // start of the matched substring
end: number; // end of the matched substring
groups: string[] = []; // the captured groups
};
使用预设语言之一的bber
您可以使用任何预设语言 :
export type LanguageName =
| "es" // Ecmascript (Javascript / Typescript / Haxe): the default
| "rs" // Rust
| "css"
| "scss"
| "sass"
| "c"
| "cpp"
| "py" // Python
| "nim";
示例
// find all semi-colons inside the rust source code
grub(rustCodeToParse, "rs").find(";");
使用自定义规则的 grubber
您可以定义 grubber 解析器的自定义规则 。 什么应该被忽略 作为"不是代码".
A 类 Rule 有下列类型:
export type Rule =
| {
expression: string | RegExp; // the expression to ignore
// if returns false, the match is ignored
onExpressionMatch?: (match: RegExpExecArray) => boolean | void;
}
| {
startAt: string | RegExp; // start of the expression to ignore
stopAt: string | RegExp; // stop of the expression to ignore
// if returns false, the match is ignored
onStartMatch?: (match: RegExpExecArray) => boolean | void;
onStopMatch?: (match: RegExpExecArray) => boolean | void;
};
例如,《公约》使用的规则 C 语言为:
const rules: Rule[] = [
{
// string
expression: /".*?[^\\](?:\\\\)*"/,
},
{
// single line comment
expression: /\/\/.*/,
},
{
// multiline comment
expression: /\/\*((?:.|\s)*?)\*\//,
},
];
对于大多数语言来说,规则相当简单,但对Ecmascript来说则变得复杂,因为
${...}语法. 希望工作已经为你完成!
{\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}你觉得呢