简体   繁体   中英

Anything before and after delimiter regex

(?=.+?,*)[^,]+

There are the results I get and expect:

"This,is,successful"

Results:

  • This
  • is
  • successful

",is also successful"

Results:

  • is also successful

The following is wrong-

"This is not successful"

Results:

  • This is not successful

I only want to match if and only if the delimiter is in the string, anything before and after the delimiter. I tried an additional look ahead with +. . but was either getting results that include everything or nothing at all when a delimiter like ',' was present.

You can use this lookarounds based regex:

(?<=,)[^,]*|[^,]*(?=,)

RegEx Demo

  • (?<=,) asserts there is a , before the match
  • (?=,) asserts there is a , after the match
  • [^,]* matches 0 or more of any character except the comma

Try the following regex:

([^,]+)?,([^,]+)|([^,]+),([^,]+)?

Tested on PHP 5.5. (The above regex works well in PHP with preg_match_all function)

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