Question

Help! I've been thrashing on this longer than I care to say. I have a string that may or may not contain a hyphen or a comma. If it does, I want everything to the left of the first occurrence of the hyphen or comma. If it does not, I want the entire string.

(.*?)[\,\-]

This is giving me the first part of the puzzle, but this returns a null for the "otherwise give me the entire string" part:

(?=(.*?)[\,\-]|.*)

Where am I missing the boat???

Was it helpful?

Solution

Try

/^[^,-]+/

i.e. in JavaScript

"one two three".match(/^[^,-]+/); //["one two three"]
"one, two three".match(/^[^,-]+/); //["one"];

[EDIT, in response to OP's comment about new requirement]

To match only if the letter 'm' is found somewhere in the string:

"one two m th,ree".match(/^(?=[\s\S]*m)[^,-]+/); //["one two m th"]
"one two th,ree".match(/^(?=[\s\S]*m)[^,-]+/); //null

OTHER TIPS

I wouldn't do it this way, but its returning a match but no contents
because the .* is inside an assertion AND uncaptured.

Usually assertions don't captur anything, but they can match.
In order to capture inside the assertion you have to include capture parenths.

Also, the same applies to assertions within assertions.

So, for a single capture group $1 you would have to do something like

 # ^(?=(.*?(?=[,-])|.*))

 ^ 
 (?=
      (                      # (1 start)
           .*? 
           (?= [,-] )
        |  .* 
      )                      # (1 end)
 )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top