运维开发网

JS正则表达式中G标志的介绍

运维开发网 https://www.qedev.com 2022-06-20 20:59 出处:网络
正则的思想都是一样的,但是具体的写法会有所不同,下面这篇文章主要给大家介绍了关于JavaScript正则表达式中g标志的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

正则的思想都是一样的,但是具体的写法会有所不同,下面这篇文章主要给大家介绍了关于JavaScript正则表达式中g标志的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下


缘起

有一天在思福社区看到一个问题,大致描述如下。

const list = ['a', 'b', '-', 'c', 'd'];const reg = /[a-z]/g;const letters = list.filter(i =gt; reg.test(i));// letters === ['a', 'c'];// 如果正则不使用`g`标志可以得到所有的字母// 为什么加入`g`之后就不可以了

对于问题,遍历中的I是一个字符,不需要G。

但就我对规律性的理解(太浅)来说,有没有G(只是全局搜索,不匹配就停)应该不会影响,这引起了我的好奇。

以上建议写如下

const reg = /[a-z]/g;reg.test('a'); // =gt; truereg.test('a'); // =gt; falsereg.test('a'); // =gt; truereg.test('a'); // =gt; falsereg.test('a'); // =gt; true


解密过程

首先可以确定的是,性能一定是g造成的。


搜索引擎

打开MDN仔细查看G logo的功能,结论和我的理解一样。

我猜应该是G可能启用了某种缓存,因为reg relative filter是全局变量,所以我把代码改成了:

const list = ['a', 'b', '-', 'c', 'd'];const letters = list.filter(i =gt; /[a-z]/g.test(i));// letters === ['a', 'b', 'c', 'd'];

向每一次遍历宣告正则性,结论是正确的,验证了我的猜想。也明白了。缓存在常规的某个地方

下面我找到相应的源代码来检查问题的原因。


源码层面

因为最近在看Rust,所以用Rust写的源码来查看。

打开项目,单击。进入vscode模式,command+p搜索regexp关键字。


进入test.rs文件,command+f search /g查找第90行中last_index()的测试。

#[test]fn last_index() { let mut context = Context::default(); let init = r#" var regex = /[0-9]+(\.[0-9]+)/g; "#; // forward 的作用:更改 context,并返回结果的字符串。 eprintln!("{}", forward(amp;mut context, init)); assert_eq!(forward(amp;mut context, "regex.lastIndex"), "0"); assert_eq!(forward(amp;mut context, "regex.test('1.0foo')"), "true"); assert_eq!(forward(amp;mut context, "regex.lastIndex"), "3"); assert_eq!(forward(amp;mut context, "regex.test('1.0foo')"), "false"); assert_eq!(forward(amp;mut context, "regex.lastIndex"), "0");}

看到有lastIndex关键字,我在这里大概猜到了问题的原因。G符号匹配后还有最后一个下标,导致问题。

我们将目光移向mod.rs文件并搜索test。

fn test()方法见第631行。

pub(crate) fn test( this: amp;JsValue, args: amp;[JsValue], context: amp;mut Context,) -gt; JsResultlt;JsValuegt; { // 1. Let R be the this value. // 2. If Type(R) is not Object, throw a TypeError exception. let this = this.as_object().ok_or_else(|| { context .construct_type_error("RegExp.prototype.test method called on incompatible value") }); // 3. Let string be ToString(S). let arg_str = args .get(0) .cloned() .unwrap_or_default() .to_string(context); // 4. Let match be RegExpExec(R, string). let m = Self::abstract_exec(this, arg_str, context); // 5. If match is not null, return true; else return false. if m.is_some() { Ok(JsValue::new(true)) } else { Ok(JsValue::new(false)) }}

在test()方法中找到了Self::abstract_exec()方法

pub(crate) fn abstract_exec( this: amp;JsObject, input: JsString, context: amp;mut Context,) -gt; JsResultlt;Optionlt;JsObjectgt;gt; { // 1. Assert: Type(R) is Object. // 2. Assert: Type(S) is String. // 3. Let exec be Get(R, "exec"). let exec = this.get("exec", context); // 4. If IsCallable(exec) is true, then if let Some(exec) = exec.as_callable() { // a. Let result be Call(exec, R, S ). let result = exec.call(amp;this.clone().into(), amp;[input.into()], context); // b. If Type(result) is neither Object nor Null, throw a TypeError exception. if !result.is_object() amp;amp; !result.is_null() { return context.throw_type_error("regexp exec returned neither object nor null"); } // c. Return result. return Ok(result.as_object().cloned()); } // 5. Perform RequireInternalSlot(R, [[RegExpMatcher]]). if !this.is_regexp() { return context.throw_type_error("RegExpExec called with invalid value"); } // 6. Return RegExpBuiltinExec(R, S). Self::abstract_builtin_exec(this, amp;input, context)}

self:: abstract _ building _ exec()方法位于Self::abstract_exec()方法中。

pub(crate) fn abstract_builtin_exec( this: amp;JsObject, input: amp;JsString, context: amp;mut Context,) -gt; JsResultlt;Optionlt;JsObjectgt;gt; { // 1. Assert: R is an initialized RegExp instance. let rx = { let obj = this.borrow(); if let Some(rx) = obj.as_regexp() { rx.clone() } else { return context.throw_type_error("RegExpBuiltinExec called with invalid value"); } }; // 2. Assert: Type(S) is String. // 3. Let length be the number of code units in S. let length = input.encode_utf16().count(); // 4. Let lastIndex be ( ToLength( Get(R, "lastIndex"))). let mut last_index = this.get("lastIndex", context).to_length(context); // 5. Let flags be R.[[OriginalFlags]]. let flags = amp;rx.original_flags; // 6. If flags contains "g", let global be true; else let global be false. let global = flags.contains('g'); // 7. If flags contains "y", let sticky be true; else let sticky be false. let sticky = flags.contains('y'); // 8. If global is false and sticky is false, set lastIndex to 0. if !global amp;amp; !sticky { last_index = 0; } // 9. Let matcher be R.[[RegExpMatcher]]. let matcher = amp;rx.matcher; // 10. If flags contains "u", let fullUnicode be true; else let fullUnicode be false. let unicode = flags.contains('u'); // 11. Let matchSucceeded be false. // 12. Repeat, while matchSucceeded is false, let match_value = loop { // a. If lastIndex gt; length, then if last_index gt; length { // i. If global is true or sticky is true, then if global || sticky { // 1. Perform Set(R, "lastIndex", +0, true). this.set("lastIndex", 0, true, context); } // ii. Return null. return Ok(None); } // b. Let r be matcher(S, lastIndex). // Check if last_index is a valid utf8 index into input. let last_byte_index = match String::from_utf16( amp;input.encode_utf16().take(last_index).collect::lt;Veclt;u16gt;gt;(), ) { Ok(s) =gt; s.len(), Err(_) =gt; { return context .throw_type_error("Failed to get byte index from utf16 encoded string") } }; let r = matcher.find_from(input, last_byte_index).next(); match r { // c. If r is failure, then None =gt; { // i. If sticky is true, then if sticky { // 1. Perform Set(R, "lastIndex", +0, true). this.set("lastIndex", 0, true, context); // 2. Return null. return Ok(None); } // ii. Set lastIndex to AdvanceStringIndex(S, lastIndex, fullUnicode). last_index = advance_string_index(input, last_index, unicode); } Some(m) =gt; { // c. If r is failure, then #[allow(clippy::if_not_else)] if m.start() != last_index { // i. If sticky is true, then if sticky { // 1. Perform Set(R, "lastIndex", +0, true). this.set("lastIndex", 0, true, context); // 2. Return null. return Ok(None); } // ii. Set lastIndex to AdvanceStringIndex(S, lastIndex, fullUnicode). last_index = advance_string_index(input, last_index, unicode); // d. Else, } else { //i. Assert: r is a State. //ii. Set matchSucceeded to true. break m; } } } }; // 13. Let e be r's endIndex value. let mut e = match_value.end(); // 14. If fullUnicode is true, then if unicode { // e is an index into the Input character list, derived from S, matched by matcher. // Let eUTF be the smallest index into S that corresponds to the character at element e of Input. // If e is greater than or equal to the number of elements in Input, then eUTF is the number of code units in S. // b. Set e to eUTF. e = input.split_at(e).0.encode_utf16().count(); } // 15. If global is true or sticky is true, then if global || sticky { // a. Perform Set(R, "lastIndex", (e), true). this.set("lastIndex", e, true, context); } // 16. Let n be the number of elements in r's captures List. (This is the same value as 22.2.2.1's NcapturingParens.) let n = match_value.captures.len(); // 17. Assert: n lt; 23^2 - 1. debug_assert!(n lt; 23usize.pow(2) - 1); // 18. Let A be ! ArrayCreate(n + 1). // 19. Assert: The mathematical value of A's "length" property is n + 1. let a = Array::array_create(n + 1, None, context); // 20. Perform ! CreateDataPropertyOrThrow(A, "index", (lastIndex)). a.create_data_property_or_throw("index", match_value.start(), context) .expect("this CreateDataPropertyOrThrow call must not fail"); // 21. Perform ! CreateDataPropertyOrThrow(A, "input", S). a.create_data_property_or_throw("input", input.clone(), context) .expect("this CreateDataPropertyOrThrow call must not fail"); // 22. Let matchedSubstr be the substring of S from lastIndex to e. let matched_substr = if let Some(s) = input.get(match_value.range()) { s } else { "" }; // 23. Perform ! CreateDataPropertyOrThrow(A, "0", matchedSubstr). a.create_data_property_or_throw(0, matched_substr, context) .expect("this CreateDataPropertyOrThrow call must not fail"); // 24. If R contains any GroupName, then // 25. Else, let named_groups = match_value.named_groups(); let groups = if named_groups.clone().count() gt; 0 { // a. Let groups be ! OrdinaryObjectCreate(null). let groups = JsValue::from(JsObject::empty()); // Perform 27.f here // f. If the ith capture of R was defined with a GroupName, then // i. Let s be the CapturingGroupName of the corresponding RegExpIdentifierName. // ii. Perform ! CreateDataPropertyOrThrow(groups, s, capturedValue). for (name, range) in named_groups { if let Some(range) = range { let value = if let Some(s) = input.get(range.clone()) { s } else { "" }; groups .to_object(context) .create_data_property_or_throw(name, value, context) .expect("this CreateDataPropertyOrThrow call must not fail"); } } groups } else { // a. Let groups be undefined. JsValue::undefined() }; // 26. Perform ! CreateDataPropertyOrThrow(A, "groups", groups). a.create_data_property_or_throw("groups", groups, context) .expect("this CreateDataPropertyOrThrow call must not fail"); // 27. For each integer i such that i ≥ 1 and i ≤ n, in ascending order, do for i in 1..=n { // a. Let captureI be ith element of r's captures List. let capture = match_value.group(i); let captured_value = match capture { // b. If captureI is undefined, let capturedValue be undefined. None =gt; JsValue::undefined(), // c. Else if fullUnicode is true, then // d. Else, Some(range) =gt; { if let Some(s) = input.get(range) { s.into() } else { "".into() } } }; // e. Perform ! CreateDataPropertyOrThrow(A, ! ToString((i)), capturedValue). a.create_data_property_or_throw(i, captured_value, context) .expect("this CreateDataPropertyOrThrow call must not fail"); } // 28. Return A. Ok(Some(a))}

self:: abstract _ building _ exec()方法中有global和last_index,所以看起来最终要执行的方法在这里。仔细看看这个方法的代码(代码写的很详细,每一步都有注释)。

在步骤12中:

lastIndex 超过文本长度且当 global 存在时将 lastIndex 置为 0

获取匹配值(match_value)

如果不是,则设置为advance_string_index()方法的返回值。

本期问题不考虑Advance_string_index(),https://tc39.es/ecma262/#sec-....

步骤13获取匹配值的endIndex。

步骤15将lastIndex设置为endIndex

至此,G符号的含义就完全明白了。常规原型链中有一个lastIndex。如果匹配为真,lastIndex不会被重置为0,最后一个位置将在下一次开始时被继承。


结论

分析问题代码

const reg = /[a-z]/g; // 声明后,lastIndex 为 0reg.test('a'); // =gt; true;第一次匹配后,lastIndex 为 1reg.test('a'); // =gt; false;第二次匹配由于 lastIndex 为 1,且字符只有一个,得到 false,将 lastIndex 置为 0reg.test('a'); // =gt; true;下面依次循环前两次的逻辑reg.test('a'); // =gt; false;reg.test('a'); // =gt; true;

关于JavaScript正则表达式中G标志的详细解释,本文到此为止。

0

精彩评论

暂无评论...
验证码 换一张
取 消