regex - Wildcard matching in Java -



regex - Wildcard matching in Java -

i'm writing simple debugging programme takes input simple strings can contain stars indicate wildcard match-any

*.wav // matches <anything>.wav (*, a) // matches (<anything>, a)

i thought take pattern, escape regular look special characters in it, replace \\* .*. , utilize regular look matcher.

but can't find java function escape regular expression. best match find pattern.quote, puts \q , \e @ begin , end of string.

is there in java allows wildcard matching without having implement algorithm scratch?

using simple regex

one of method's benefits can add together tokens besides * (see adding tokens @ bottom).

search: [^*]+|(\*)

the left side of | matches chars not star the right side captures stars grouping 1 if grouping 1 empty: replace \q + match + e if grouping 1 set: replace .*

here working code (see output of online demo).

input: audio*2012*.wav

output: \qaudio\e.*\q2012\e.*\q.wav\e

string subject = "audio*2012*.wav"; pattern regex = pattern.compile("[^*]+|(\\*)"); matcher m = regex.matcher(subject); stringbuffer b= new stringbuffer(); while (m.find()) { if(m.group(1) != null) m.appendreplacement(b, ".*"); else m.appendreplacement(b, "\\\\q" + m.group(0) + "\\\\e"); } m.appendtail(b); string replaced = b.tostring(); system.out.println(replaced);

adding tokens

suppose want convert wildcard ?, stands single character, dot. add together capture grouping regex, , exclude matchall on left:

search: [^*?]+|(\*)|(\?)

in replace function add together like:

else if(m.group(2) != null) m.appendreplacement(b, ".");

java regex wildcard

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -