[英]Regex: problem creating matching pattern
Having some problems figuring out the regex to match this: 在找出正则表达式以解决此问题时遇到一些问题:
function Array() { [native code] }
I'm trying to only match the text that will occur where "Array" is. 我试图只匹配将出现在“数组”位置的文本。
Are you trying to find out what type a variable is in javascript? 您是否要找出javascript中变量的类型? If that's what want you can just compare the object's constructor to the constructor that you think created it:
如果那是您想要的,则可以将对象的构造函数与您认为创建该对象的构造函数进行比较:
var array = new Array();
if(array.constructor == Array)
alert("Is an array");
else
alert("isn't an array");
This isn't really the best way to go about things in javascript. 这实际上并不是处理javascript的最佳方法。 Javascript doesn't have a type system like C# does that guarantees you that a variable will have certain members if it's created by a certain constructor because javascript is a pretty dynamic languages and anything that an object gets from its constructor can be overwritten at runtime.
Javascript没有像C#这样的类型系统,它可以确保如果某个变量是由某个构造函数创建的,则该变量将具有某些成员,因为javascript是一种非常动态的语言,对象从其构造函数获取的任何内容都可以在运行时覆盖。
Instead it's really better to use duck typing and ask your objects what they can do rather than what they are: http://en.wikipedia.org/wiki/Duck_typing 取而代之的是,最好使用鸭子输入并询问您的对象它们可以做什么而不是它们是什么: http : //en.wikipedia.org/wiki/Duck_typing
if(typeof(array.push) != "undefined")
{
// do something with length
alert("can push items onto variable");
}
In Perl, you'd use: 在Perl中,您将使用:
m/^\s*function\s+(\w+)\s*\(/;
The variable ' $1
' would capture the function name. 变量“
$1
”将捕获函数名称。
If the function
keyword might not be at the start of the line, then you have to work (a little) harder. 如果
function
关键字可能不在该行的开头,那么您就必须加倍努力。
[Edit: two ' \\s*
' sequences added.] [编辑:添加了两个'
\\s*
'序列。]
Question about whether this works...here's my test case: 关于这是否有效的问题...这是我的测试用例:
Test script: 测试脚本:
while (<>)
{
print "$1\n" if (m/^\s*function\s+(\w+)\s*\(/);
}
Test input lines (yes, deliberately misaligned): 测试输入线(是,故意未对准):
function Array() { ... }
function Array2 () { ... }
func Array(22) { ... }
Test output: 测试输出:
Array
Array2
Tested with Perl 5.10.0 on Solaris 10 (SPARC): I don't believe the platform or version is a significant factor - I'd expect it to work the same on any plausible version of Perl. 在Solaris 10(SPARC)上使用Perl 5.10.0进行了测试:我认为平台或版本不是一个重要因素-我希望它在任何可能的Perl版本上都可以正常工作。
So subsequently, I've gotten this which almost works: 因此,随后,我得到了几乎可行的方法:
[function\s]((\S+)+)(?=\(\))
However, it still matches the space before Array 但是,它仍然与Array之前的空格匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.