javaregex

Java regex to match a pattern


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*=.*?");

Solution

  • 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