Matching the first occurrence of each letter in string

问题内容:

What I’d like to do is match the first occurrence of two or more letters, so for example, I’d like to highlight A and F from the string below:

"ASDFASDFASDFASDF"

But only the first A and only the first F

I’ve tried:

/A{1}F{1}/i

But no joy…

Any ideas appreciated…

问题评论:

4  
What is the purpose? Also, why can’t you use something simple, like .indexOf()
    
I agree on the indexOf. If you have no other way, you can give a try to ^[^A]*(A) when searching for first occurence of A (as there is no variable length lookbehind using javascript RegExp). Capturing group will let you know the occurence position in the string.
    
Unless you want to do something with the position of A and F in the string, simply includes or indexOf will do.

答案:

答案1:

This should give you the match you want:

/^(a).*?(f)/i
  • ^ asserts position at start of the string
  • .*? matches any character (except for line terminators)
  • *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)

答案评论:

    
Only when F is always is behind A, which almost certainly is not the case.
    
That doesn’t seem to work: regex101.com/r/IxkI5p/4 – it matches everything from A to F – but I just need A and F
– JFM
2 hours ago
    
Another example… I would like to highlight (wrap around some span tags) the words shark and trip. But only the first instance of each word:
– JFM
2 hours ago
    
I am on a shark fishing trip, a fishing trip for shark I am on.
– JFM
2 hours ago
    
so words 5 and 7 would be highlighted if you see what I mean?
– JFM
2 hours ago

原文地址:

https://stackoverflow.com/questions/47752698/matching-the-first-occurrence-of-each-letter-in-string

添加评论

友情链接:蝴蝶教程