简体   繁体   中英

Get string between special characters using regex in Java

I am trying to get a string between the "@function" and "@" for the input string:

inputText = "@function square @default 2 @type Int @brief squares default number"

What would the regex expression be in order to get the text between '@function' and '@'?

In order for the following (in Java):

Pattern p = Pattern.compile( some magic regex expression... );
Matcher m = p.matcher(inputText);
functionName = m.group;
System.out.println(functionName);

to print "square"

regex:

@function(.*?)@

This should place "square" into the first capturing group. You can then use Matcher.group(int) to grab that group. As in the below code:

functionName = m.group(1);

group(int group) Returns the input subsequence captured by the given group during the previous match operation.

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)

EDIT

added '\\s' to trim whitespace

https://regex101.com/r/PH54FV/1

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