我用它#(\s|^)([a-z0-9-_]+)#i
来大写每个单词的每个第一个字母,如果它在像破折号这样的特殊标记之后,我也希望它大写字母(-)
现在它显示:
This Is A Test For-stackoverflow
我想要这个:
This Is A Test For-Stackoverflow
对我有什么建议/样品吗?
我不是专业人士,所以尽量保持简单让我理解。
我用它#(\s|^)([a-z0-9-_]+)#i
来大写每个单词的每个第一个字母,如果它在像破折号这样的特殊标记之后,我也希望它大写字母(-)
现在它显示:
This Is A Test For-stackoverflow
我想要这个:
This Is A Test For-Stackoverflow
对我有什么建议/样品吗?
我不是专业人士,所以尽量保持简单让我理解。
+1 用于单词边界,这是一个可比较的 Javascript 解决方案。这也解释了所有格:
var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon";
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
实际上不需要匹配完整的字符串,只需匹配第一个非大写字母,如下所示:
'~\b([a-z])~'
如果你想使用纯正则表达式,你必须使用\u
.
要转换此字符串:
这是对stackoverflow的测试
进入
这是对 Stackoverflow 的测试
您必须输入:
(.+)-(.+)
要捕获“-”之前和之后的值,然后替换它,您必须输入:
$1-\u$2
如果它在 bash 中,则必须输入:
echo "This Is A Test For-stackoverflow" | sed 's/\(.\)-\(.\)/\1-\u\2/'
对于 JavaScript,这是一个适用于不同语言和字母的解决方案:
const originalString = "this is a test for-stackoverflow"
const processedString = originalString.replace(/(?:^|\s|[-"'([{])+\S/g, (c) => c.toUpperCase())
它匹配任何\S
以字符串开头^
、空格\s
或任何字符开头的非空白字符-"'([{
,并将其替换为其大写变体。
我使用 javascript 的解决方案
function capitalize(str) {
var reg = /\b([a-zÁ-ú]{3,})/g;
return string.replace(reg, (w) => w.charAt(0).toUpperCase() + w.slice(1));
}
使用 es6 + javascript
const capitalize = str =>
str.replace(/\b([a-zÁ-ú]{3,})/g, (w) => w.charAt(0).toUpperCase() + w.slice(1));
/<expression-here>/g
[a-zÁ-ú]
在这里,我考虑了字母表中的所有字母,包括大写字母和重音符号。例如:sábado de J aneiro às 19 h。sexta - feira de janeiro às 21 e horas[a-zÁ-ú]{3,}
所以我要删除一些不够大的字母,\b([a-zÁ-ú]{3,})
最后,我只保留选择的完整单词。必须使用 () 来隔离最后一个表达式才能工作。完成此操作后,我仅将更改应用于小写单词
string.charAt(0).toUpperCase() + w.slice(1); // output -> Output
加入两者
str.replace(/\b(([a-zÁ-ú]){3,})/g, (w) => w.charAt(0).toUpperCase() + w.slice(1));
结果:
Sábado de Janeiro às 19h。Sexta -费拉热内卢às 21 e Horas
这是我的 Python 解决方案
>>> import re
>>> the_string = 'this is a test for stack-overflow'
>>> re.sub(r'(((?<=\s)|^|-)[a-z])', lambda x: x.group().upper(), the_string)
'This Is A Test For Stack-Overflow'
在此处阅读“积极的后视”:https ://www.regular-expressions.info/lookaround.html
这将使
REAC De Boeremeakers
从
反应器
(?<=\A|[ .])(?<up>[a-z])(?=[a-z. ])
使用
Dim matches As MatchCollection = Regex.Matches(inputText, "(?<=\A|[ .])(?<up>[a-z])(?=[a-z. ])")
Dim outputText As New StringBuilder
If matches(0).Index > 0 Then outputText.Append(inputText.Substring(0, matches(0).Index))
index = matches(0).Index + matches(0).Length
For Each Match As Match In matches
Try
outputText.Append(UCase(Match.Value))
outputText.Append(inputText.Substring(Match.Index + 1, Match.NextMatch.Index - Match.Index - 1))
Catch ex As Exception
outputText.Append(inputText.Substring(Match.Index + 1, inputText.Length - Match.Index - 1))
End Try
Next