简体   繁体   English

在逗号或空格上匹配正则表达式,但不能两者都匹配

[英]Matching regular expression on comma or space, but not both

I need to have a regular expression that replaces commas and spaces with a comma and a space, but leaves it alone if it's already a comma and a space in sequence. 我需要有一个正则表达式,用逗号和空格替换逗号和空格,但是如果它已经是逗号和空格,则将其保留。

Example: 例:

44,55 90 should turn into 44, 55, 90 44,55 90应该变成44,55,90

but, 44, 55, 90 when entered again should remain the same. 但是再次输入44、55、90时应保持不变。

I initially tried /[\\s,]/g but it of course replaces any comma or space with both a comma and space, so 44, 55, 90 became 44, , 55, , 90 我最初尝试使用/[\\s,]/g但是它当然用逗号和空格替换了任何逗号或空格,所以44,55,90变成了44,,55,,90

The answer is very simple / ,?|,/g 答案很简单/ ,?|,/g
Or if you want to remove any amount of white space before comma / *,?| /g 或者,如果您想在逗号/ *,?| /g之前删除任何空白, / *,?| /g / *,?| /g
Or if you want go crazy go with this /\\s*,\\s*|\\s+/g this will replace any extra spacing before , and after it and do all good stuf as erlier. 或者,如果您想疯了,请使用此/\\s*,\\s*|\\s+/g它将替换之前,之后的所有多余空格,并做得更好。

This will work for the test string, assuming you're looking to fix strings with digits, commas and spaces, and not other combinations of characters. 假设您要使用数字,逗号和空格(而不是其他字符组合)来修复字符串,这将适用于测试字符串。

Search for this: 搜索:

\\d(,)\\d|\\d([ ]{1,},[ ]{0,})\\d|\\d([ ]{1,})\\d

Replace capture group 1 with comma , and a space, 用逗号替换捕获组1 ,和一个空格, .

That should handle any real or potential white space with quantifiers checking for multiple whitespaces. 那应该使用量词检查多个空白来处理任何实际或潜在的空白。

Test string with 6 matches : 有6个匹配项的测试字符串

44,55 90 ,44 , 55 , 90 , 1234 ,

You could go the other way and replace everything that is not digits with anything you want, using a negated character class: 您可以采用另一种方法,使用否定的字符类将所有不是数字的东西替换为您想要的任何东西:

'999 123,098b7b7b7b7b,,,123^&*()43'.replace(/[^\d]+/g,', ');
//"999, 123, 098, 7, 7, 7, 7, 123, 43"

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

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