简体   繁体   English

javascript 正则表达式检查第一个和最后一个字符是否相似?

[英]javascript regex to check if first and last character are similar?

Is there any simple way to check if first and last character of a string are the same or not, only with regex?是否有任何简单的方法来检查字符串的第一个和最后一个字符是否相同,仅使用正则表达式?

I know you can check with charAt我知道你可以用 charAt 检查

var firstChar = str.charAt(0);
var lastChar = str.charAt(length-1);
console.log(firstChar===lastChar):

I'm not asking for this: Regular Expression to match first and last character我不是要这个: 匹配第一个和最后一个字符的正则表达式

You can use regex with capturing group and its backreference to assert both starting and ending characters are same by capturing the first caharacter.您可以将正则表达式与捕获组及其反向引用一起使用,以通过捕获第一个字符来断言起始字符和结束字符相同。 To test the regex match use RegExp#test method.要测试正则表达式匹配,请使用RegExp#test方法。

 var regex = /^(.).*\\1$/; console.log( regex.test('abcdsa') ) console.log( regex.test('abcdsaasaw') )

Regex explanation here :正则表达式解释在这里:

  1. ^ asserts position at start of the string ^断言字符串开头的位置
  2. 1st Capturing Group (.)第一捕获组(.)
  3. .* matches any character (except newline) - between zero and unlimited times, as many times as possible, giving back as needed (greedy) .*匹配任何字符(换行符除外) - 在零次和无限次之间,尽可能多次,根据需要回馈(贪婪)
  4. \\1 matches the same text as most recently matched by the 1st capturing group \\1匹配与第一个捕获组最近匹配的相同文本
  5. $ asserts position at the end of the string $断言字符串末尾的位置

The . . doesn't include newline character, in order include newline update the regex.不包含换行符,为了包含换行符更新正则表达式。

 var regex = /^([\\s\\S])[\\s\\S]*\\1$/; console.log( regex.test(`abcd sa`) ) console.log( regex.test(`ab c dsaasaw`) )

Refer : How to use JavaScript regex over multiple lines?参考: 如何在多行上使用 JavaScript 正则表达式?

Regex explanation here :正则表达式解释在这里:

  1. [.....] - Match a single character present [.....] - 匹配存在的单个字符
  2. \\s - matches any whitespace character (equal to [\\r\\n\\t\\f\\v ] ) \\s - 匹配任何空白字符(等于[\\r\\n\\t\\f\\v ]
  3. \\S - matches any non-whitespace character (equal to [^\\r\\n\\t\\f ] ) \\S - 匹配任何非空白字符(等于[^\\r\\n\\t\\f ]

finally [\\s\\S] is matches any character.最后[\\s\\S]匹配任何字符。

You can try it你可以试试看

 const rg = /^([\w\W]+)[\w\W]*\1$/; console.log( rg.test(`abcda`) ) console.log( rg.test(`aebcdae`) ) console.log( rg.test(`aebcdac`) )

    var rg = /^([a|b])([a|b]+)\1$|^[a|b]$/;

    console.log(rg.test('aabbaa'))

    console.log(rg.test('a'))

    console.log(rg.test('b'))

    console.log(rg.test('bab'))

    console.log(rg.test('baba'))

This will make sure that characters are none other than a and b which have the same start and end.这将确保字符不是别人,而是具有相同开始和结束的 a 和 b。

It will also match single characters because they too start and end with same character.它还将匹配单个字符,因为它们也以相同的字符开始和结束。

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

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