简体   繁体   中英

Java Regex Word Extract exclude with special char

below are the String values

"method" <in> abs
("method") <in> abs
method <in> abs

i want to extract only the Word method , i tries with below regex

"(^[^\\\\<]*)" its included the special char also

O/p for the above regex

"method"
("method")
method

my expected output

method
method
method
^\\W*(\\w+)

You can use this and grab the group 1 or capture 1 .See demo.

https://regex101.com/r/sS2dM8/20

A couple of words on your "(^[^<]*)" regex: it does not match because it has beginning of string anchor ^ after " , which is never the case. However, even if you remove it "([^<]*)" , it will not match the last case where " and ( are missing. You need to make them optional. And note the brackets must escaped, and the order of quotes and brackets is different than in your input.

So, your regex could be fixed as

^\(?"?(\b[^<]*)\b"?\)?(?=\s+<)

See demo

However, I'd suggest using a replaceAll approach:

String rx = "(?s)\\(?\"?(.*?)\"?\\)?\\s+<.*";
System.out.println("\"My method\" <in> abs".replaceAll(rx, "$1"));

See IDEONE demo

If the strings start with ("My method , you can also add ^ to the beginning of the pattern: String rx = "(?s)^\\\\(?\\"?(.*?)\\"?\\\\)?\\\\s+<.*"; .

The regex (?s)^\\\\(?\\"?(.*?)\\"?\\\\)?\\\\s+<.* matches:

  • (?s) makes . match a newline symbol (may not be necessary)
  • ^ - matches the beginning of a string
  • \\\\(? - matches an optional (
  • \\"? - matches an optional "
  • (.*?) - matches and captures into Group 1 any characters as few as possible
  • \\"? - matches an optional "
  • \\\\)? - matches an optional )
  • \\\\s+ - matches 1 or more whitespace
  • < - matches a <
  • .* - matches 0 or more characters to the end of string.

With $1 , we restore the group 1 text in the resulting string.

In fact it is not too complicated.
Here is my answer:

        Pattern pattern = Pattern.compile("([a-zA-Z]+)");
        String[] myStrs = {
                "\"method\"",
                "(\"method\")",
                "method"
                };

        for(String s:myStrs) {
            Matcher matcher = pattern.matcher(s);
            if(matcher.find()) {
                System.out.println( matcher.group(0) );
            }
        }

The output is:

method
method
method

You just need to use:

[a-zA-Z]+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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