Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

what is the difference between PHP regex and javascript regex

i am working in regex my regex is /[([^]s]+).([^]]+)]/g this works great in PHP for [http://sdgdssd.com fghdfhdhhd] but when i use this regex for javascript it do not match with this input string

my input is [http://sdgdssd.com fghdfhdhhd]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In JavaScript regex, you must always escape the ] inside a character class:

[([^]s]+).([^]]+)]

See the regex demo

JS parsed [^] as *any character including a newline in your regex, and the final character class ] symbol as a literal ].

In this regard, JS regex engine deviates from the POSIX standard where smart placement is used to match [ and ] symbols with bracketed expressions like [^][].

The ] character is treated as a literal character if it is the first character after ^: [^]abc].

In JS and Ruby, that is not working like that:

You can include an unescaped closing bracket by placing it right after the opening bracket, or right after the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. This does not work in JavaScript, which treats [] as an empty character class that always fails to match, and [^] as a negated empty character class that matches any single character. Ruby treats empty character classes as an error. So both JavaScript and Ruby require closing brackets to be escaped with a backslash to include them as literals in a character class.

Related:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...