I`d like to find some statements in a file. And I need to print out element and sub element name.The statement like
set element elemName subElem sumElemName
If a element or sub element name includes one or more spaces, the entire string must be enclosed within double quotes. Double quotes are dispensable if there is no space in a element or sub element name. So following statements are valid.
set element "aaa bbb" subElem "ccc"
set element "aaa bbb" subElem ccc
set element "aaa" subElem "ccc"
I tried to write two expressions to meet some cases. But how to write one regular expression to meet all cases?
String regex = "^\\s*set\\s+element\\s+\"(.*)\"\\s+subElem\\s+\"(.*)\"\\s*$";
String regex = "^\\s*set\\s+element\\s+(?<!\")(\\S+)\\s+subElem\\s+(?<!\")(\\S+)\\s*$";
You may match substrings inside double quotes or a chunk of non-whitespace chars as the elemNames
:
String regex = "^\\s*set\\s+element\\s+(\"[^\"]*\"|\\S+)\\s+subElem\\s+(\"[^\"]*\"|\\S+)\\s*$";
See the regex demo
The (\"[^\"]*\"|\S+)
pattern matches
\"[^\"]*\"
- a "
, then any 0+ chars other than "
and then a "
|
- or \S+
- 1+ non-whitespace chars.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With