Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

What will be the Regex for my required pattern

I have a pattern like -

public static void myMethod(int Val , String Val){}

so public\static\void\myMethod(int\sVal\s,\sString\sVal)

but if my method have more space than one like public static it fails. So how to make a concrete pattern .

Moreover the part inside the bracket is not working, suggest me the way to resolve.

Upvotes: 0

Views: 82

Answers (4)

Matt Ball
Matt Ball

Reputation: 359776

Use \s+ to match one or more occurrence, and \s* to match zero or more occurrences. Escape the parentheses so that they are not interpreted as grouping operators.

public\s+static\s+void\s+myMethod\s*\(\s*int\s+Val\s*,\s*String\s+Val\s*\)

That said, it looks like you are trying to parse Java code with a regular expression. This is not possible since Java (like the infamous [X]HTML) is not a regular language.

Upvotes: 4

maerics
maerics

Reputation: 156404

Try using the "one or more" modifier (+) to match multiple occurrences:

public\s+static\s+void\s+myMethod...

Upvotes: 1

Ben Roux
Ben Roux

Reputation: 7426

A few things, but you are on the right track. Replace your \s with \s+ to indicate 1 or more whitespace characters.

Also, your parens are not working because they are reserved regex characters. You must escape them to have them be literally interpreted

/public\s+static\s+void\s+myMethod\s*\(\s*int\s+Val\s*,\s*String\s+Val\s*\)/

Upvotes: 1

OscarRyz
OscarRyz

Reputation: 199215

use \s+ instead

Upvotes: 1

Related Questions