在R语言中统计符合特定规则的@开头字符数量
Counting Valid @-Prefixed Substrings in a String
Hey there! Let's break down how to solve this problem step by step. First, let's restate the requirements clearly to make sure we're on the same page:
We need to count how many substrings in a given string meet these rules:
- Starts with
@ - Only contains alphanumeric characters (letters/numbers),
@, and underscores (_) - Total length is 10 characters or less
In your example string: vec <- " @_Jim98 Did you turn off the stove @9am?"
@_Jim98is valid: it starts with @, only uses allowed characters, and is 7 characters long (well under 10)@9am?is invalid: it includes a?which isn't allowed, so it gets excluded- Final count should be 1
Solution Code (R)
Since your example uses R syntax, here's a practical implementation using regex and string manipulation:
# Example input string vec <- " @_Jim98 Did you turn off the stove @9am?" # Step 1: Extract all @-prefixed substrings (stop at spaces) candidates <- stringr::str_extract_all(vec, "@[^\\s]+")[[1]] # Step 2: Define regex pattern for valid substrings # ^$ ensures we check the entire substring; allowed chars are @, letters, numbers, _; length 1-10 valid_pattern <- "^[@a-zA-Z0-9_]{1,10}$" # Step 3: Filter candidates to keep only valid ones valid_matches <- candidates[grepl(valid_pattern, candidates)] # Step 4: Count the valid matches count <- length(valid_matches) # Output the result cat("Total valid substrings:", count, "\n")
How This Works
- Extracting Candidates:
str_extract_all(vec, "@[^\\s]+")grabs every substring that starts with@and continues until the next space. For your example, this gives us["@_Jim98", "@9am?"]. - Validity Check: The regex
^[@a-zA-Z0-9_]{1,10}$makes sure:- The entire substring only uses allowed characters (no
?,!, etc.) - The total length is between 1 and 10 characters (since @ takes up one spot, we can have 0-9 more allowed characters)
- The entire substring only uses allowed characters (no
- Counting: We use
greplto test each candidate against the pattern, then count how many pass.
When you run this code, it will output Total valid substrings: 1—exactly what we expect from your example.
内容的提问来源于stack exchange,提问作者user9605051
相关产品推荐
相关产品推荐

