简体   繁体   English

正则表达式:删除除字母和分隔符之外的所有内容

[英]Regex: remove everything except the letters and separator

I am currently using replace statements to replace certain parts of a string.我目前正在使用替换语句来替换字符串的某些部分。 I think my code is a bit over the top and could be simplified:我认为我的代码有点过头了,可以简化:

const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5'
locales = locales.replace('-','_')
locales = locales.replace(';q=','')
locales = locales.replace(/[0-9]/g,'')
locales = locales.replace('.','')

In the end, I want to remove everything except for the locale from the string using regex and replace - with _ .最后,我想使用正则表达式从字符串中删除除语言环境之外的所有内容,并将-替换为_ I would like the final string to look like this:我希望最终的字符串看起来像这样:

'fr_CH, fr, en, de, *'

You could replace and search for two small characters and possible following dash and some more upper case characters or a star.您可以替换和搜索两个小字符,并可能在破折号和一些大写字符或星号之后。

 const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5', parts = locales.replace(/-/g, '_').match(/[az]{2}_*[AZ]*|\*/g).join(', '); console.log(parts);

An even shorter approach which relaces all parts after semicolon (inclusive) until following comma without converting/matching to an array an joining back to a string.一种更短的方法,它替换分号(包括)之后的所有部分,直到逗号之后,而不转换/匹配到数组并连接回字符串。

 const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5', parts = locales.replace(/-/g, '_').replace(/;[^,]+/g, '') console.log(parts);

A carefully chosen regular expression can strip out the weightings in one replacement.精心挑选的正则表达式可以在一次替换中去掉权重。 A second switches the hyphens - for underscores _第二个切换连字符-用于下划线_

const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5';
newLocales = locales.replace(/;q=\d*\.\d*/g,'').replace(/-/g,'_');
console.log(newLocales);   //  fr_CH, fr, en, de, *

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

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