Very simple Java regex not giving expected result -
today first day learning regular expressions (literally no background before this) through chapter strings in book thinking in java 4th edition. pulling hair out why regular expression not matching region of input string. have tested in regex101 , result expected, in java (which can't test on regex101 site admittedly) result different.
edit: doing exercise 10 in chapter
regex: n.w\s+h(a|i)s
input string: java has regular expressions
expected result: match found in region "now has"
of input string
actual result: no match found
my relevant code:
import java.util.regex.*; public class foo { public static void main(string[] args) { // note: i've tested passing regex arg command line // "n.w\s+h(a|i)s" string regex = "n.w\\s+h(a|i)s"; string input = "java has regular expressions"; pattern p = pattern.compile(regex); matcher m = p.matcher(input); // starting @ beginning of input string, match in // region of input string boolean matchfound = m.lookingat(); system.out.println("match found: " + matchfound); } } /* output -> match found: false */
use m.find()
instead of m.lookingat()
you can print m.group()
please check code below.
import java.util.regex.*; public class foo { public static void main(string[] args) { // note: i've tested passing regex arg command // line // "n.w\s+h(a|i)s" string regex = "n.w\\s+h(a|i)s"; string input = "java has regular expressions"; pattern p = pattern.compile(regex); matcher m = p.matcher(input); // starting @ beginning of input string, match in // // region of input string boolean matchfound = m.find(); system.out.println("match found: " + matchfound); system.out.println("matched string is: " + m.group()); } }
the javadoc of lookingat() is
public boolean lookingat()
attempts match input sequence, starting @ beginning of region, against pattern. matches method, method starts @ beginning of region; unlike method, not require entire region matched.
if match succeeds more information can obtained via start, end, , group methods.
returns:true if, , if, prefix of input sequence matches matcher's pattern
that means, method expects regex matches @ beginning of input string.
this method not used frequently, effect modify regex "^n.w\\s+h(a|i)s"
, , use find()
method. puts limitation regex matches @ beginning of input string.
Comments
Post a Comment