用于匹配 JavaScript 中存在的子字符串的正则表达式

regex to match substring exist in javascript

本文关键字:字符串 正则表达式 存在 JavaScript 用于      更新时间:2023-09-26

我想编写一个正则表达式来匹配我的网址是否有 gmt.php。例如:

如果我的网址http://example.com/gmt.php?a=1这是真的

如果我的网址http://example.com/ac.php那么它是假

我试过了:

/^([a-z0-9])$/.test('gmt.php');

但它并不完美。是的,我只需要正则表达式而不是子字符串匹配indexOf谢谢。

为什么不简单地索引

url.indexOf( "gmt.php" ) != -1 //outputs true if it exists

对于正则表达式(不确定为什么要正则表达式来做这么简单的事情;))

/gmt'.php/.test('http://example.com/gmt.php?a=1 ');

/gmt.php/.test('http://example.com/gmt.php?a=1 ');//since . is . outside []
/

^([a-z0-9])$/.test('GMT.php');

但它并不完美。

因为/^([a-z0-9])$/只会匹配一个字母数字字符

试试这个:/gmt.php/.test(url)

<html>
<head><title>foo</title>
<script>
function foo(url) {
  alert(/gmt.php/.test(url));
}
</script>
</head>
<body>
<form>
<input type="text" id="text" size="40"><input type="button" onclick="foo(document.getElementById('text').value)">
</form>
</body>

var reg = /^(?:https?:'/'/'w+'.'w+'/)?'w+'.'w+'?'w+'='w+$/;
var url1 = 'http://example.com/gmt.php?a=1';
var url2 = 'http://example.com/ac.php';
var url3 = 'gmt.php?a=1';
var url4 = 'gmt.php'
    console.log(reg.test(url1));
    console.log(reg.test(url2));
    console.log(reg.test(url3));
    console.log(reg.test(url4));

如有其他故障数据,请@me,