简体   繁体   中英

How do I match a single word in Javascript Regex?

I just want to match one word (\\w+) after a pattern in javascript.

Here is my simple test code:

(new RegExp("apple:\w+")).test("apple:asdf");

However, I am being told by javascript that the pattern does not match. This goes against pretty much everything I'm used to about regex matching. Even when I tested it on regex101.com I got a match.

What is the convention used for matching a word?

First, you need to escape that slash inside your string literal, otherwise it'll be just lost:

const slashIsLost = "apple:\w+";
console.log(slashIsLost); // apple:w+

const slashIsEscaped = "apple:\\w+";
console.log(slashIsEscaped ); // apple:\w+

Second, you need to remember that \\w matches both letters, digits and _ character. So you might better use [A-Za-z] character class instead - or just bite the first pair and make RegExp case-insensitive with i flag.

As a sidenote, it's really not clear why don't you just use RegExp literal here:

/apple:[a-z]+/i.test('apple:asdf')

Your thought is good, but you need to escape your backslashes when using the RegEx constructor. MDN recommends:

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

An alternative is the regular expression literal syntax:

Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.

Try this code:

const re = /apple:\w+/
const str = "apple"
re.test(str)

Check out the MDN docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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