Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to build a regular expression (regex) for slangs and emoticons
    text
    copied!<p>i need to build a regex to match slangs (i.e. lol, lmao, imo, etc..) and emoticons (i.e. :), :P, ;), etc...).</p> <p>i followed the example at <a href="http://www.coderanch.com/t/497238/java/java/Regular-Expression-Detecting-Emoticons" rel="nofollow">http://www.coderanch.com/t/497238/java/java/Regular-Expression-Detecting-Emoticons</a>. however, this method/approach is failing for me. </p> <p>for example, let's say i need to match the slang "od". i create a Pattern as follows. Pattern pattern = Pattern.compile(Pattern.quote("od"));</p> <p>let's say i need to match the slang "od" in the following test sentence, "some methods are bad." empirically, there is one match on the word "methods" in the string, which is not what i want.</p> <p>i did read some of the javadoc and some of the tutorial regarding java and regex, but i still can't figure this out.</p> <p>by the way, i am using Java 6 (though i've looked and reference the java 5 api doc).</p> <p>if regex is not the best way to go, i am opened to other solutions as well. thanks in advance for any help/pointers. the following code gets me 3 matches and is based on the link above.</p> <pre><code>String regex = "od"; Pattern pattern = Pattern.compile(Pattern.quote(regex)); String str = "some methods are bad od od more text"; Matcher matcher = pattern.matcher(str); while(matcher.find()) { System.out.println(matcher.group()); } </code></pre> <p>the following code returns no matches and is based on the responses so far.</p> <pre><code>String regex = "\bod\b"; Pattern pattern = Pattern.compile(regex); //Pattern pattern = Pattern.compile(Pattern.quote(regex)); //this fails String str = "some methods are bad od od more text"; Matcher matcher = pattern.matcher(str); while(matcher.find()) { System.out.println(matcher.group()); } </code></pre> <p>after the two helpful responses below, i will post the correct/desired code snippet here.</p> <pre><code>String regex = "(\\bod\\b)|(\\blmao\\b)"; Pattern pattern = Pattern.compile(regex); String str = "some methods are bad od od more text lmao more text"; Matcher matcher = pattern.matcher(str); while(matcher.find()) { System.out.println(matcher.group()); } </code></pre> <p>this code is correct or as desired because empirically, it gives me 3 matches (2 od and 1 lmao). sorry, i wish i am stronger with regex using java (and just regex in general). thanks for your help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload