-1

How can I check via regex if a string is: - letters-only (a-z, insensitive) - does not have an equal sign

ex.

  • class - should pass
  • class="something" - should fail
  • class=someclass - should fail

So far I have this:

[a-zA-Z][^=]+

However when I tested it on regex101 with class=someclass It results with:


 - Match 1 - Full match 0-5 class
 - Match 2 - Full match  6-15 someclass

What am I missing here? Thanks!

kzaiwo
  • 1,558
  • 1
  • 16
  • 45
  • 2
    Why not just `^[a-z]+$`? – Nick Jun 12 '20 at 02:01
  • The input is HTML ? – Gilles Quénot Jun 12 '20 at 02:05
  • @GillesQuenot yes, vue/html attributes. I am using the regex to sort the attributes using this VS Code extension: https://marketplace.visualstudio.com/items?itemName=rbalet.vscode-sorting-attrs. And the order is configured via regex: https://github.com/mrmlnc/posthtml-attrs-sorter#order. Basically I need a regex for single-word keywords (for vue, without any characters, specifically the = sign). – kzaiwo Jun 12 '20 at 02:10

2 Answers2

0

One solution is to wrap your solution with ^ and $ to force it to match against the full line, rather than searching for matches within the line. This assumes the multiline flag is enabled, which should be the default on regex101.

Proof: https://regex101.com/r/2aYZF1/1

mrossman
  • 561
  • 4
  • 12
0

You need to properly anchor the regex with /^...$/. Here is a working snippet that takes your examples:

var str1 = 'class';
var str2 = 'class="something"';
var str3 = 'class=something';
var re = /^[a-z]+$/i;
var result1 = re.test(str1);
var result2 = re.test(str2);
var result3 = re.test(str3);
console.log('- result1: ' + result1);
console.log('- result2: ' + result2);
console.log('- result3: ' + result3);

Result:

- result1: true
- result2: false
- result3: false
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20