简体   繁体   English

正则表达式测试字符串结尾吗?

[英]RegEx test for string ending?

I'm horrible at RegEx and I need a regex to test if a certain string ends a certain way. 我在RegEx感到很恐怖,我需要一个regex来测试某个字符串是否以某种方式结束。 For example, if the RegEx tests for ending with foo, "somestringfoo" -> True and "someotherFoostring" -> False. 例如,如果RegEx测试以foo结尾,则“ somestringfoo”-> True和“ someotherFoostring”-> False。 It needs to be case sensitive and work with alphanumeric and underscore. 它必须区分大小写并可以使用字母数字和下划线。 Here is what I've got, but I can't get it to work: 这是我所拥有的,但我无法使其正常工作:

var test = RegExp.test('/foo$/');

您可以这样进行:

/foo$/.test("somestringfoo")

this should do the work: 这应该做的工作:

function isFoo(string){
  var pattern = /foo$/;  
  return pattern.test(string);
}

test is a method of the regexp object, so it would be /foo$/.test(someString) or new Regexp("foo$").test(someString) . test是regexp对象的方法,因此它将是/foo$/.test(someString)new Regexp("foo$").test(someString)

However, testing a string for ending with a certain substring does not need regular expressions, see endsWith in JavaScript . 但是,测试以某个子字符串结尾的字符串不需要正则表达式,请参见JavaScript中的endsWith

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

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