1

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.

4
  • 2
    You don't need Regexp, use String's lastIndexOf instead Commented Sep 24, 2015 at 16:24
  • Thanks @hindmost but I need to use this in a simple replace. Without going capturing and using function replace. Commented Sep 24, 2015 at 16:26
  • You can still use lastIndexOf to replace. substr/substring will help. Commented Sep 24, 2015 at 16:29
  • @hindmost i think problem with lastIndexOf is what if doesnt have the -ID in there? Commented Sep 24, 2015 at 16:43

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks Anubhava, but i need it to not select the -ID at the end :( And I cant use capuring :(
Thanks for your edit it works for my case but is it possible to do my gorup thing? I was hoping to learn it if possible.
There was some trick like [^-[^I[^D]]]] but Ill accept your solution as soon as stack allows me.
That kind of trick becomes very clumsy for longer text so I would suggest that only when lookahead isn't available.
Ah the problem with this, is that if it doesnt have -ID at the end it comes with no match :(
|
1

This works for all test cases

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

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

1 Comment

Thank you this is so interesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.