JavaRush /Java Blog /Random EN /Regular expressions: find a word/part of a word
eGarmin
Level 41

Regular expressions: find a word/part of a word

Published in the Random EN group
If you need to find a word or substring, a good solution is to use the control operator from the regular expression toolkit . It is indispensable when you need to find something that follows something else.
Simple example
String str = "программируем"; Pattern p = Pattern.compile(".*программ(?=ируем).*"); Matcher m = p.matcher(str); if(m.matches()){ System.out.println("Нашел!"); }else{ System.out.println("Не нашел!"); }
1. Search from the front
In the example above, if you need to find “programming”, but do not need to search for “programming”, you should use the following pattern: .*программ(?=ируем).* ?= – search in front for the presence of a word/part of a word; ?! – search from the front for the absence of a word/part of a word.
2. Search from behind
Searching from behind works in a similar way. You need to use ?<= to search for a word/part of a word behind it and ? .*(?<=programs)we.* The word “program” matches this pattern, but the word “polish” does not.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION