简体   繁体   中英

Javascript regex all characters up till word

I have a strings like this:

blah-ha-ID:
asdf

I want to match all characters up till the final -ID:

So my initial regex was:

^[^-]+

This worked until words starting have hypnes in them. So in the example above, in blah-ha-ID: it would select up till blah when it should have got blah-ha .

So I was trying something like this, i want to repeat all characters that are not -ID

^[^-ID]+

But of course that wont work. I can't use capturing, and I need it to exclude the final -ID

More then workarounds I was hoping to learn how to do this, i recall there was a way to repeat up till a "word" in these character classes.

You can use this regex:

/^(.+?)(?=-ID|$)/

This will match 1 or more characters from start to literal -ID or line end. -ID is in a positive lookahead so it won't be matched.

RegEx Demo

This works for all test cases

^.*(?=-ID)|.*[^-ID:]

where I have added the degenerate case of -ID: on a line by itself.

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