0

I am trying to match some criteria in my sentence. I could come up with a regex pattern, but unfortunately though some are matching but still it is not matching properly for others. In a sentence, I need to keep the alphanumeric string only while keeping those strings which have "-" inbetween and " ' " apostrophe. Example

  • hello
  • hello-world
  • year's

my regex is: (?=\S*|['-])([a-zA-Z0-9'-]+)

currently the above regex is matching "---" (should not be correct) but not matching "year's"

Thank you

2 Answers 2

0

I think you are looking for:

[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)*

Note that (?=\S*|['-]) is an always true assertion since \S* matches the empty string.

1
  • fantastic ... this is what did the job, so to get the required strings I just had to enclose within the brackets - ([a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)*) .. thank you !
    – Anis
    Commented Sep 10, 2017 at 21:51
0

you can use the regex

^(?=\S*[-'])(?!\S*[-']{2,})([-a-zA-Z0-9']+)$

see the regex101 demo. It ensures that the string has at least 1 [-'] and they are not consecutive

1
  • this is actually not matching my first example. i.e "hello" and also other alphanumeric such as "hello123". though matching "hello-world" and "world's"
    – Anis
    Commented Sep 10, 2017 at 21:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.