Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

javascript - Regex to match words with hyphens and/or apostrophes

I was looking for a regex to match words with hyphens and/or apostrophes. So far, I have:

(w+([-'])(w+)?[']?(w+))

and that works most of the time, though if there's a apostrophe and then a hyphen, like "qu'est-ce", it doesn't match. I could append more optionals, though perhaps there's another more efficient way?

Some examples of what I'm trying to match: Mary's, High-school, 'tis, Chambers', Qu'est-ce.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use this pattern

(?=S*['-])([a-zA-Z'-]+)

Demo

(?=                 # Look-Ahead
  S                # <not a whitespace character>
  *                 # (zero or more)(greedy)
  ['-]              # Character in ['-] Character Class
)                   # End of Look-Ahead
(                   # Capturing Group (1)
  [a-zA-Z'-]        # Character in [a-zA-Z'-] Character Class
  +                 # (one or more)(greedy)
)                   # End of Capturing Group (1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...