javascript 仅匹配 Unicode 字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13210194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:05:12  来源:igfitidea点击:

Match only unicode letters

javascriptregex

提问by user1767962

i have the following regex that allows only alphabets :

我有以下只允许字母的正则表达式:

     /[a-zA-Z]+/

     a = "abcDF"
     if (a.match(/[a-zA-Z]+/) == a){
        //Match
     }else{
        //No Match
     } 

How can I do this using p{L} (universal - any language like german, english etc.. )

我如何使用 p{L}(通用 - 任何语言,如德语、英语等......)

What I tried :

我试过的:

  a.match(/[p{l}]+/)
  a.match(/[\p{l}]+/)
  a.match(/p{l}/)
  a.match(/\p{l}/)

but all returned null for the letter a = "aB"

但是对于字母 a = "aB" 都返回 null

采纳答案by Tim Pietzcker

Starting with ECMAScript 2018, JavaScript finally supports Unicode property escapesnatively.

从 ECMAScript 2018 开始,JavaScript 终于原生支持Unicode 属性转义

For older versions, you either need to define all the relevant Unicode ranges yourself. Or you can use Steven Levithan's XRegExppackage with Unicode add-onsand utilize its Unicode property shortcuts:

对于旧版本,您需要自己定义所有相关的 Unicode 范围。或者,您可以将 Steven Levithan 的XRegExp包与 Unicode 附加组件一起使用,并利用其 Unicode 属性快捷方式:

var regex = new XRegExp("^\p{L}*$")
var a = "abc??üéèê"
if (regex.test(a)) {
    // Match
} else {
    // No Match
}

回答by Daniel

If you are willing to use Babelto build your javascript then there's a babel-plugin I have released which will transform regular expressions like /^\p{L}+$/or /\p{^White_Space}/into a regular expression that browsers will understand.

如果你愿意使用Babel来构建你的 javascript,那么我发布了一个 babel-plugin,它可以将正则表达式像/^\p{L}+$//\p{^White_Space}/转换成浏览器可以理解的正则表达式。

This is the project page: https://github.com/danielberndt/babel-plugin-utf-8-regex

这是项目页面:https: //github.com/danielberndt/babel-plugin-utf-8-regex