正则表达式分裂骆驼案

时间:2013-08-22 11:34:23

标签: javascript regex

我在JavaScript中有一个正则表达式,使用以下代码(后来我从here获得)将我的驼峰字符串字符串拆分为大写字母:

"MyCamelCaseString"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); })

因此返回:

"My Camel Case String"

哪个好。但是,我想把它提升一个档次。有人可以帮助我使用正则表达式,只有当前一个字符为小写且后者为大写时才会分裂。

因此,上面的例子将是我期望的结果,但如果我这样做:

"ExampleID"

然后我回来了:

"Example ID"

而不是

"Example I D"

因为它在每个大写字母中分裂并忽略它之前的任何内容。

希望有道理!谢谢:)。

14 个答案:

答案 0 :(得分:54)

我的猜测是将/([A-Z])/替换为/([a-z])([A-Z])/,将' $1'替换为'$1 $2'

"MyCamelCaseString"
    .replace(/([a-z])([A-Z])/g, '$1 $2');
对于计为小写字符的数字,

/([a-z0-9])([A-Z])/

console.log("MyCamelCaseStringID".replace(/([a-z0-9])([A-Z])/g, '$1 $2'))

答案 1 :(得分:39)

"MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')

输出:

"My Camel Case String"

答案 2 :(得分:20)

如果你想要一个小写单词数组:

"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase());

如果你想要一串小写单词:

"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase()).join(' ');

如果你想分开单词但保留外壳:

"myCamelCaseString".replace(/([a-z])([A-Z])/g, '$1 $2')

答案 3 :(得分:3)

您好我没有看到demo,感谢@michiel-dral



var tests =[ "camelCase",
             "simple",
             "number1Case2"]

function getCamelCaseArray(camel) {
  var reg = /([a-z0-9])([A-Z])/g;
  return camel.replace(reg, '$1 $2').split(' ');
}

function printTest(test) {
document.write('<p>'+test + '=' + getCamelCaseArray(test)+'</p>');
}

tests.forEach(printTest);
&#13;
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
  </body>

</html>
&#13;
&#13;
&#13;

答案 4 :(得分:3)

不使用正则表达式-也可以使用单词边界\B

console.log("MyCamelCaseString".replace(/(\B[A-Z])/g, ' $1'));

答案 5 :(得分:2)

我发现,这个问题的答案都不能在所有情况下都有效,对于unicode字符串也不是完全有效,因此这是一个可以完成所有工作的方法,包括破折号和下划线表示法拆分。

let samples = [
  "ThereIsWay_too  MuchCGIInFilms These-days",
  "UnicodeCanBeCAPITALISEDTooYouKnow",
  "CAPITALLetters at the StartOfAString_work_too",
  "As_they_DoAtTheEND",
  "BitteWerfenSie-dieFußballeInDenMüll",
  "IchHabeUberGesagtNichtÜber",
  "2BeOrNot2Be",
  "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
];

samples.forEach(sample => console.log(sample.replace(/([^[\p{L}\d]+|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}[\p{Ll}\d])|(?<=[\p{L}\d])(?=\p{Lu}[\p{Ll}\d]))/gu, '-').toUpperCase()));

如果您不希望数字被视为小写字母,那么:

let samples = [
  "2beOrNot2Be",
  "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
];

samples.forEach(sample => console.log(sample.replace(/([^\p{L}\d]+|(?<=\p{L})(?=\d)|(?<=\d)(?=\p{L})|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})|(?<=[\p{L}\d])(?=\p{Lu}\p{Ll}))/gu, '-').toUpperCase()));

答案 6 :(得分:1)

我更喜欢使用数组而不是字符串。它更容易调试,更灵活。这是实际的export default createBottomTabNavigator({ myStack1: { screen: MyStack1, navigationOptions: ({ screenProps }) => ({ tabBarLabel: screenProps && screenProps.myStack1 }) }, myStack2: { screen: MyStack2, navigationOptions: ({ screenProps }) => ({ tabBarLabel: screenProps && screenProps.myStack2 }) } }, { initialRouteName: 'myStack1', tabBarOptions: { showLabel: true } } ); 而不是join。我没有处理字符串中的空格,但是您可以轻松地修剪每个元素。

replace

答案 7 :(得分:1)

有时camelCase字符串包含缩写,例如:

PDFSplitAndMergeSamples
PDFExtractorSDKSamples
PDFRendererSDKSamples
BarcodeReaderSDKSamples

在这种情况下,以下函数将起作用,它将字符串分割成两个单独的字符串:

function SplitCamelCaseWithAbbreviations(s){
   return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
}

示例:

function SplitCamelCaseWithAbbreviations(s){
   return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
}

console.log(SplitCamelCaseWithAbbreviations('PDFSplitAndMergeSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFExtractorSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFRendererSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('BarcodeReaderSDKSamples'));

答案 8 :(得分:0)

您可以结合使用regExreplacetrim

"ABCMyCamelCaseSTR".replace(/([A-Z][a-z0-9]+)/g, ' $1 ')
                   .replace(/\s{2}/g," ").trim()

// ABC My Camel Case STR

答案 9 :(得分:0)

如果您也想大写字母并在数字之间添加空格,这是可行的。

const str = 'this1IsASampleText';
str.charAt(0).toUpperCase() + value.slice(1); // Capitalize the first letter
str.replace(/([0-9A-Z])/g, ' $&'); // Add space between camel casing

结果:

This 1 Is A Sample Text    

答案 10 :(得分:0)

我最近遇到了这个问题,需要做同样的事情:

employeeID 应该呈现为 Employee ID

我发现来自 convert case library 的这个 zellwk 加上一些额外的 reduce 函数对我有用:

import { toTitle } from "./convert-case.js";

// NB. Assumes sequential single chars can be concatenated
// ex. N B A Finals => NBA Finals
const reducer = (total, currentValue, currentIndex, arr) => {
  if (
    currentValue.length === 1 &&
    !(currentIndex > 0 && arr[currentIndex - 1].length > 1)
  ) {
    return total + currentValue;
  } else {
    return total + " " + currentValue;
  }
};

const concatSingleChars = (title) => {
  const arrTitle = title.split(" ");
  return arrTitle.reduce(reducer);
};

const convertCase = (str) => {
  const s = toTitle(str);
  return concatSingleChars(s);
};

const tests = [
  "colName",
  "This_Is_A_title",
  "And_How_About_thisOne",
  "MaryHadALittleLamb",
  "employeeID",
  "N B A Finals",
  "N B A Finals in L A",
  "I Love L A"
];

const titles = tests.map((test) => {
  return convertCase(test);
});

console.log(titles);

答案 11 :(得分:0)

如果你像我一样有一个像驼峰大小写的值,例如:

thisIsMyCamelCaseValue 其中第一个字母小写

function fromCamelCase(value) {
    const spaced = value.replace(/([a-z])([A-Z])/g, '$1 $2');
    return spaced.charAt(0).toUpperCase() + spaced.slice(1);
}

答案 12 :(得分:-1)

a = 'threeBlindMice'
a.match(/[A-Z]?[a-z]+/g) // [ 'three', 'Blind', 'Mice' ]

是我发现的最简单的方法,用于简单的骆驼/标题案例分割。

答案 13 :(得分:-3)

此RegExp字符串

.replace("/([a-zA-Z][a-z]*)/g",...);