简体   繁体   English

正则表达式从字符串中删除前导和尾随特殊字符和空格

[英]Regex to remove leading and trailing special characters and spaces from string

I'm trying to find a regex to remove all leading/trailing spaces as well as all leading/trailing special characters.我试图找到一个正则表达式来删除所有前导/尾随空格以及所有前导/尾随特殊字符。

If I have the string:如果我有字符串:

test = '~!#@$@  hello this is a #! test  ^^#!^^    '

I'd like it to return as:我希望它返回为:

'hello this is a #! test'

So special characters and spaces in between the first and last letter are preserved, but all leading/trailing ones are cut out.因此保留了第一个和最后一个字母之间的特殊字符和空格,但所有前导/尾随字符都被删除。 Right now I have this:现在我有这个:

test.replace(/[^a-zA-Z ]/g,"").replace(/^\s+|\s+$/g, "")

which returns:返回:

'hello this is a  test'

so it is removing all special characters and leading/trailing spaces.所以它正在删除所有特殊字符和前导/尾随空格。 How can I preserve that "#?"我怎样才能保留那个“#?” between "a" and "test"?在“a”和“test”之间?

By using the unicode flag u you can use the Unicode Categories for Letters \p{L} and Numbers \p{N} in a negative character class [^...] .通过使用 unicode 标志u ,您可以在负字符 class [^...]中使用字母\p{L}和数字\p{N}的 Unicode类别
And match them at the start ^ or |并在开头匹配它们^| at the end $ to get anything that's not a letter or number and is trailing or leading.在最后$得到任何不是字母或数字的尾随或前导的东西。

Pattern:图案:

^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$

Test Snippet:测试片段:

 let test = '~;#@$@ hello this is a #. test ^^#,^^ '; test = test.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu; ''); document.write('['+test+']');

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

相关问题 正则表达式删除所有前导和尾随特殊字符? - Regex remove all leading and trailing special characters? 如何使用正则表达式删除空格、特殊字符和前导数字? - How to remove spaces, special characters and leading numbers with regex? 如何从给定的 html 字符串中删除前导和尾随空格? - How to remove leading and trailing white spaces from a given html string? 如何从字符串中删除空格和特殊字符? - How to remove spaces and special characters from string? 正则表达式允许特殊字符但不允许前导/尾随空格 - regex to allow special characters but not leading/trailing white space 使用正则表达式删除分隔符周围的尾随和前导空格 - Remove trailing and leading white spaces around delimiter using regex Javascript 从多行字符串中删除前导和尾随空格,并用逗号替换其余的空格块 - Javascript remove leading and trailing spaces from multiline string and replace the rest of whitespace chunks with commas 删除字符串中的空格,特殊字符并将其转换为小写 - Remove spaces from a string, special characters and convert it to lowercase 从字符串中删除前导零和尾随零 - Remove leading and trailing zeros from a string 如何从输入文本中删除前导和尾随空格? - How to remove leading and trailing white spaces from input text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM