gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
regex how to get the group captured
- User
regex how to get the group captured
- Assistant
To get the text captured by a group in a regex match depends on the programming language or tool you are using. Here's a general overview with examples in some popular languages:
1. Python
import re text = "Hello 123 World" pattern = r"Hello (\d+) World" match = re.search(pattern, text) if match: print(match.group(1)) # Output: 123group(1)returns the content of the first capturing group.group(0)returns the entire match.
2. JavaScript
const text = "Hello 123 World"; const regex = /Hello (\d+) World/; const match = text.match(regex); if (match) { console.log(match[1]); // Output: 123 }match[1]contains the first capturing group.match[0]is the full match.
3. Java
import java.util.regex.*; public class Main { public static void main(String[] args) { String text = "Hello 123 World"; Pattern pattern = Pattern.compile("Hello (\\d+) World"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.println(matcher.group(1)); // Output: 123 } } }