0

I am new to Java. I would like to write a Java regex to match a pattern and retrieve the value. I need to match the pattern below:

\# someproperty=somevalue // this is a new property

\#someproperty=somevalue // this is a new property

I have to match the above patterns (which may contains spaces) and I need to retrieve "someproperty" and "somevalue".

I tried with the pattern below, but it just matches only someproperty=somevalue , without "#" at the beginning. What can I try next?

Pattern propertyKeyPattern = Pattern.compile("^\\s*(\\S+?)\\s*=.*?");
3
  • 1
    Remove the ^ or add a # after it. Commented Nov 27, 2012 at 6:12
  • Is # this is a new property a part of string? Or a comment? Commented Nov 27, 2012 at 6:13
  • You don't need a reluctant matching at the end. Just remove ? and add $ to it. BTW, if you are using Matcher.matches, then the anchors are implicit, you don't need to put them. Commented Nov 27, 2012 at 6:16

2 Answers 2

2

If you want to match the whole string and find patterns, such as "\# someproperty =some value". Try regular Expression

^\\#\s*(\S+?)\s*=(.*)$

as Java string, it is

"^\\\\#\\s*(\\S+?)\\s*=(.*)$"

The match result for string \# someproperty = a some value is

matches() = Yes

find()    = Yes

group(0)  = \# someproperty = a some value

group(1)  = someproperty

group(2)  = a some value
Sign up to request clarification or add additional context in comments.

Comments

0

String a=yourString.replaceAll("[^\w\s]"," "); By using this you will get "someproperty" and "somevalue" string then u can check it. For more post your question clearly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.