简体   繁体   中英

Java - Regex to get if word contains all letters of another one

Is it possible to create java regex that could define if one word ( base ) contains all letters from another word ( sample frow which regex is created) exactly?

For example

Input : base = 'Subexpressions', sample1 = 'Nubs' Output : True

Input : base = 'Subexpressions', sample2 = 'Expert' Output : False

Explanation: base contains all letters from sample1 but doesn't contain 't' from sample2 .

For a regex approach, here's how you could do it programmatically.

  1. Make a list of letters: Subexpressions => subexprion
  2. Build a series of lookaheads with the letters, and anchor it: ^(?=.*s)(?=.*u)etc(?=.*n)$
  3. Run that regex against the string. It will act as an AND, because the lookaheads check one by one if a letter is present in the target string. If you have a match, bingo.

Of course, running strstr 10 times (once for each character) also works.

Note: Some engines may report strangely for a zero-width match, so for safety you can add a single dot after the lookaheads, ensuring that you have at least one char in the match:

^(?=.*s)(?=.*u)etc(?=.*n)$

You don't care about the char, just about whether there is a match at all.

This problem doesn't really need regex. Just use this simple approach:

  1. Set a boolean variable found to true
  2. Iterate sample variable character by character
  3. Check presence of each character in your base string variable
  4. Set found to false if a character is not found and bail out of loop

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