简体   繁体   English

Java正则表达式匹配模式

[英]Java regex to match a pattern

I am new to Java. 我是Java新手。 Please help me with a Java regex to match a pattern and retrieve the value. 请帮我使用Java正则表达式匹配模式并检索值。 I need to match the pattern bellow: 我需要匹配下面的模式:

\# 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" . 我必须匹配上面的模式(可能包含空格),我需要检索"someproperty""somevalue"

I tried with the pattern below, but it just matches only someproperty=somevalue , without "#" at the beginning. 我尝试使用下面的模式,但它只匹配someproperty=somevalue ,开头没有"#" Please help me out. 请帮帮我。

Pattern propertyKeyPattern = Pattern.compile("^\\s*(\\S+?)\\s*=.*?");

If you want to match the whole string and find patterns, such as " \\# someproperty =some value ". 如果要匹配整个字符串并查找模式,例如“ \\# someproperty =some value ”。 Try regular Expression 尝试正则表达式

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

as Java string, it is 作为Java字符串,它是

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

The match result for string \\# someproperty = a some value is 字符串\\# someproperty = a some value的匹配结果\\# someproperty = a some value

matches() = Yes

find()    = Yes

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

group(1)  = someproperty

group(2)  = a some value

String a=yourString.replaceAll("[^\\w\\s]"," "); String a = yourString.replaceAll(“[^ \\ w \\ s]”,“”); By using this you will get "someproperty" and "somevalue" string then u can check it. 通过使用它你将得到“someproperty”和“somevalue”字符串,然后你可以检查它。 For more post your question clearly. 更多地发布您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM