简体   繁体   English

Javascript正则表达式-从字符串获取函数名称

[英]Javascript regex - getting function name from string

I am trying to get a function name from a string in javascript. 我试图从javascript中的字符串获取函数名称。

Let's say I have this string: 假设我有以下字符串:

function multiply($number) {
    return ($number * 2);
}

I am using the following regex in javascript: 我在javascript中使用以下正则表达式:

/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g

However, what is selected is multiply( . This is wrong. What I want is the word multiply without the the ( , though the regex should keep in mind that the function name must be attached an ( . 但是,选择的是multiply( 。这是错误的。我想要的是不包含(的单词) multiply ,尽管正则表达式应记住,函数名称必须附加一个(

I can't get this done. 我做不到。 How can I make the proper regex for this? 我该如何为此制作合适的正则表达式? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work. 我知道这不是我真正应该做的事情,并且它对错误非常敏感,但是我仍然想尝试使这项工作生效。

Just replace last \\) with (?=\\() 只需将最后一个\\)替换为(?=\\()

`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]

You can use: 您可以使用:

var name = functionString.match(/function(.*?)\(/)[1].trim();

Get anything between function and the first ( (using a non-gredy quantifier *? ), then get the value of the group [1] . And finally, trim to remove surrounding spaces. 获取function和第一个function之间的任何function ( (使用非灰色量词*? ),然后获取组[1]的值。最后, trim以除去周围的空间。

Example: 例:

 var functionString = "function dollar$$$AreAllowedToo () { }"; var name = functionString.match(/function(.*?)\\(/)[1].trim(); console.log(name); 

Notes: 笔记:

  1. The characters allowed in javascript for variable names are way too much to express in a set. javascript中允许变量名称使用的字符太多,无法在集合中表达。 My answer takes care of that. 我的回答解决了这个问题。 More about this here 有关此的更多信息
  2. You may want to consider the posibility of a comment between function and ( , or a new line too. But this really depends on how you intend to use this regex. 您可能要考虑function(之间的注释的可能性,或者也要换行。但这实际上取决于您打算如何使用此正则表达式。

take for examlpe: 举例:

function /*this is a tricky comment*/ functionName // another one
   (param1, param2) {

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM