简体   繁体   中英

Regex Match All Except Leading and Trailing Spaces Around Commas (including comma)

I'm trying to match everything except commas and any spaces around them. However, I would like it to match spaces between words. This is what I have so far:

/[^,\s][a-zA-Z0-9_ !@#$%^&*()]+/gi

It's matching everything except commas and trailing spaces, but it's including the leading spaces. Here's the link to test it regex101 .

I'm trying to wrap span tags around key terms. This is what I would want the end result to be:

<span>Some text</span>   ,    <span>Some more     text</span>

I'm currently using

.replace(/([^,\s][a-zA-Z0-9_ !@#$%^&*()]+)/gi, "<span>$1</span>")

and it updates the span tags in a contenteditable div. I'm using it to place bubbles using CSS around key terms, and are updated after every input. Any help would be greatly appreciated! Thanks!

The regex would be:

([\s\S]+?)(\s*,\s*|$)

then within replace() method back-reference to both capturing groups:

 const regex = /([\\s\\S]+?)(\\s*,\\s*|$)/g; const str = `uncased is a test , vertical this is a tests 80000 , bertical 80000 , vertical #303 cardio endo, kljafklj\\$!asdfkj`; // The substituted value will be contained in the result variable const result = str.replace(regex, '<span>$1</span>$2'); console.log(result); 

Does this do the trick ?

/((?:(\w|[-!@#$%^&*()])+( (\w|[-!@#$%^&*()]))*)+)/g

Or

/((?:(\w|[-!@#$%^&*()])+( {1,MAX_NUMBER_OF_SPACES}(\w|[-!@#$%^&*()]))*)+)/g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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