Batuhan B
Batuhan B

Reputation: 1855

Giving inputs to java regex

I have a regex like below one :

"\\t'AUR +(username) .*? /ROLE=\"(my_role)\".*$"

username and my_role parts will be given from args. So they always change when the script is starting. So how can i give parameters to that part of regex ?

Thanks for your helps.

Upvotes: 0

Views: 58

Answers (4)

hiddenbit
hiddenbit

Reputation: 2243

You should escape special characters in dynamic strings using Pattern.quote. To put the regex parts together you can simply use string concatenation like this:

String quotedUsername = Pattern.quote(username);
String quotedRole = Pattern.quote(my_role);
String regexString = "\\t'AUR +(" + quotedUsername + 
                     ") .*? /ROLE=\"(" + quotedRole + ")\".*$";

I think mixing regular expressions with format strings when using String.format can make the regex harder to understand.

Upvotes: 1

sdanzig
sdanzig

Reputation: 4500

Try this for an example:

String patternString = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String formatted = String.format(patternString, username,my_role);
System.out.println(formatted);
Pattern pattern = Pattern.compile(patternString);

You can run a working example here: http://ideone.com/93YeNg

Upvotes: 0

anubhava
anubhava

Reputation: 784968

Define regex like this:

String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";

// assuming userName and myRole are your arguments
String regex = String.format(fmt, userName, myRole);

Upvotes: 1

user484261
user484261

Reputation:

Use string format or straight string concat to construct the regex before passing it to compile ...

Upvotes: 0

Related Questions