简体   繁体   English

正则表达式-捕获两个字符串之间的所有下划线

[英]regex - capture all underscores between two strings

In this string(this is not my code, just sample input) 在这个字符串中(这不是我的代码,只是示例输入)

var b_1 = goog.require('a_b_b');
console.log(b_1.b);

a_b_b should be renamed to abb , so all underscores inside a goog.require('...') statement should be renamed to a . a_b_b应该重命名为abb ,因此goog.require('...')语句中的所有下划线都应重命名为a . .

I came up with this regex: 我想出了这个正则表达式:

/goog\.require\('(?:[^_]*(_)[^_]*)*'\)/g

Explanation: 说明:

goog\.require\('   literal
(?:                non-capturing group
[^_]*              match anything except underscore
(_)                capture underscore
[^_]*              match anything except underscore
)                  end of non-capturing group
*                  there can be more than one underscore in a goog.require statement
'\)                literal

But this only captures the last underscore. 但这仅捕获了最后一个下划线。 How can I capture all underscores in a goog.require('...') statement? 如何在goog.require('...')语句中捕获所有下划线?

I don't know if it's useful, but I'm replacing the underscores with javascript, so look behinds are not (natively) supported. 我不知道它是否有用,但是我用JavaScript代替了下划线,因此(本机)不支持回顾。

To be clear: I only want the underscores inside the goog.require('...') statement to be replaced, so the underscore in b_1 should not be replaced. 需要明确的是:我只希望goog.require('...')语句中的下划线, b_1不应替换b_1的下划线。

You can use this regex: 您可以使用此正则表达式:

var result = str.replace(/goog\.require\('[^']+'\)/g, function (match) {
    return match.replace(/_/g, '.');
});

This first finds all occurrences that match the goog.require('str') form and replaces all occurrences of '_' with '.' 这首先查找与goog.require('str')格式匹配的所有匹配项,然后将所有'_'替换为'.' .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式用下划线替换两个指定字符串之间的空格 - regex to replace spaces with underscores between two specified strings 正则表达式以获取两个字符串之间的所有字符串 - RegEx to get ALL Strings between two Strings 在下划线,星号和波浪号之间匹配字符串的正则表达式 - Regex that match strings in between underscores, asterisks & tilde 正则表达式匹配两个相同字符串之间的所有字符串 - Regex to match all the strings between two identical strings 正则表达式:匹配两个符号之间的所有字符串但捕获组 - Regex: Match all string but capture groups between two symbols Javascript中两个不同字符串正则表达式之间的所有文本 - All texts Between Two Different Strings Regex in Javascript 使用javascript中的正则表达式获取两个花括号之间的所有字符串 - Get all strings between two curly braces using regex in javascript 获取两个字符之间的所有字符串的数组(正则表达式+ JavaScript) - Get array of all strings between two characters (Regex + JavaScript) JS RegEx匹配两个字符串之间但没有两个字符串的所有字符(包括换行符)? - JS RegEx to match all characters (including newline) between two strings but without the two strings? 两个非组之间的正则表达式捕获组 - Regex capture group between two non groups
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM