Learn R Programming

llmflow (version 3.0.2)

extract_code: Generic function to extract code of any specified language

Description

This function provides a flexible way to extract code blocks of any language from a string by specifying the language identifier(s).

Usage

extract_code(input_string, language, case_sensitive = FALSE)

Value

A character vector containing the extracted code

Arguments

input_string

A string containing code blocks

language

Language identifier(s) to extract (e.g., "r", "python", c("bash", "sh"))

case_sensitive

Whether the language matching should be case-sensitive (default: FALSE)

Examples

Run this code
# Extract R code
text <- "```r\nx <- 1:10\n```"
extract_code(text, "r")

# Extract multiple language variants
text <- "```bash\necho 'test'\n```\n```sh\nls -la\n```"
extract_code(text, c("bash", "sh"))

# Case-sensitive extraction
text <- "```R\nplot(1:10)\n```\n```r\nprint('hello')\n```"
extract_code(text, "r", case_sensitive = TRUE) # Only matches lowercase 'r'
extract_code(text, "r", case_sensitive = FALSE) # Matches both 'R' and 'r'

# Extract custom language
text <- "```julia\nprintln(\"Julia code\")\n```"
extract_code(text, "julia")

# Extract YAML configuration
config_text <- "
Here's the configuration:
```yaml
database:
  host: localhost
  port: 5432
  name: mydb
```
"
extract_code(config_text, "yaml")

# Extract multiple TypeScript and JavaScript blocks
mixed_text <- "
TypeScript:
```typescript
interface User {
    name: string;
    age: number;
}
```

JavaScript:
```js
const user = {name: 'John', age: 30};
```
"
# Extract TypeScript
extract_code(mixed_text, "typescript")
# Extract both TypeScript and JavaScript
extract_code(mixed_text, c("typescript", "js"))

Run the code above in your browser using DataLab